diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..94bb3b78af635fdd0606a27484199f82e21b24e3 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/first-hunk-only.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py +index 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.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..110ccd55c4ac71cad711cc67aca5c2fb8433aa43 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/adapter.json @@ -0,0 +1,127 @@ +{ + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..32b24bf61b2a0c101f3b7a0027c5e869baeda623 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/instruction.md @@ -0,0 +1,46 @@ +Click 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 + +```python +import click + +@click.group() +@click.pass_context +def cli(ctx): + ctx.obj = 'test' + +@cli.command() +@click.pass_obj +def 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: + +```python +import 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..ff9318dbfa5bf04d3671a352908eb15bd1089d19 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/metadata.json @@ -0,0 +1,744 @@ +{ + "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=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-00.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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..23e6ba490715456428816f76439c8697b667260c --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provenance.json @@ -0,0 +1,88 @@ +{ + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..65788ab8bf9a304d14262cec4c5c9f4918375248 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provided-gold.diff @@ -0,0 +1,95 @@ +diff --git a/src/click/decorators.py b/src/click/decorators.py +index 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 + diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d24604535b4f8e0d5b3469eaa402299a4eb5d054 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/solution/solve.sh @@ -0,0 +1,101 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/decorators.py b/src/click/decorators.py +index 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.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/task.toml b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..c56391757438082b4e1e272ee9ab8958d296ecd4 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "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=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-00.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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..46920e2b0b5a09a0b0ba88f93829cefbd61ac6f4 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/decorators.py b/src/click/decorators.py +index 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) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..b078427269df73120ccac47f4acf2599b65f963d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "594c017a98d20582b453a9cad99c02d53e61877c433dc50069c0f2a6b6c683a1", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "25a0cdb9062832fe71637b0b37ac378f4ea93c3934adacf96c3bbc9363144c78", + "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": "114f21e6ad316811e51eb53fcb27665e9439be40be21d8d81663a59973cef19a", + "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": "d1deda1ebf791aa785d213b26e00362bca09dd9d", + "source_completion_sha256": "7e330b4fb14adac48e79964cf506b0f7067d5a3ff8ede49a321c92bb1997ee85", + "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__5wzhcy9r", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "61ec89c70c89b0546e9a633eeda224ac31cbf94f182b4b8a829858dc33d600ea", + "is_fork": true, + "learner_path": "tasks/f808044c40e0e9f7d468872f/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/d1deda1ebf791aa785d213b26e00362bca09dd9d/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": "5f9e78aae9222258ff7bcd1489bc728d7efe416d136f686fe212fef08ece2583", + "provenance_path": "tasks/f808044c40e0e9f7d468872f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d1deda1ebf791aa785d213b26e00362bca09dd9d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "56d33cb7871bf7281709be20e714c0a688f670ec", + "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__5wzhcy9r", + "task_sha256": "e9caf0c2de44efb002d0f5b0994e30ff50959ff223c2a0b3784f4b8de31fa15c", + "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__5wzhcy9r", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..068b6eed57e76733f851075fcebd4c4998a54651 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/instruction.md @@ -0,0 +1,41 @@ +Context stack behavior broken after recent changes + +#### Description + +The click context stack is not working correctly. When trying to access the current context, it's returning the wrong context or causing IndexError exceptions. + +#### Steps/Code to Reproduce + +```python +import click + +@click.command() +@click.pass_context +def test_cmd(ctx): + # This should work but fails + current = click.get_current_context() + print(f"Current context: {current}") + +if __name__ == '__main__': + test_cmd() +``` + +Also affects progress bars and color handling: + +```python +import click + +# This will fail with IndexError +with click.progressbar(range(5)) as bar: + for item in bar: + pass + +# Color handling also broken +click.secho('hello world', fg='blue', color=True) +``` + +The context stack seems to be accessing the wrong index, causing various parts of click that depend on the context to fail with IndexError or return unexpected results. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..7913557f0f9a61413379a4e8383e2c661a57531d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/metadata.json @@ -0,0 +1,744 @@ +{ + "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_context.py::test_global_context_object", + "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_secho_non_text[123-\\x1b[45m123\\x1b[0m]", + "tests/test_termui.py::test_progressbar_yields_all_items", + "tests/test_termui.py::test_progress_bar_update_min_steps", + "tests/test_testing.py::test_with_color", + "tests/test_testing.py::test_with_color_errors", + "tests/test_utils.py::test_echo_color_flag" + ], + "PASS_TO_PASS": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_context_meta", + "tests/test_context.py::test_make_pass_meta_decorator", + "tests/test_context.py::test_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_init_exceptions", + "tests/test_termui.py::test_progressbar_iter_outside_with_exceptions", + "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_secho", + "tests/test_termui.py::test_secho_non_text[test-test]", + "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_fast_edit", + "tests/test_termui.py::test_edit", + "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_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_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-00.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", + "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_prompts", + "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_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", + "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_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_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", + "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": "56d33cb7871bf7281709be20e714c0a688f670ec", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "d1deda1ebf791aa785d213b26e00362bca09dd9d" + }, + "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_arguments.py", + "/testbed/tests/test_basic.py", + "/testbed/tests/test_chain.py", + "/testbed/tests/test_command_decorators.py", + "/testbed/tests/test_commands.py", + "/testbed/tests/test_compat.py", + "/testbed/tests/test_custom_classes.py", + "/testbed/tests/test_defaults.py", + "/testbed/tests/test_formatting.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_normalization.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_shell_completion.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_context.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/globals.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2783386, + "task_id": "pallets__click.fde47b4b.combine_file__5wzhcy9r", + "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__5wzhcy9r", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "61ec89c70c89b0546e9a633eeda224ac31cbf94f182b4b8a829858dc33d600ea", + "is_fork": true, + "learner_path": "tasks/f808044c40e0e9f7d468872f/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/d1deda1ebf791aa785d213b26e00362bca09dd9d/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": "5f9e78aae9222258ff7bcd1489bc728d7efe416d136f686fe212fef08ece2583", + "provenance_path": "tasks/f808044c40e0e9f7d468872f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d1deda1ebf791aa785d213b26e00362bca09dd9d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "56d33cb7871bf7281709be20e714c0a688f670ec", + "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__5wzhcy9r", + "task_sha256": "e9caf0c2de44efb002d0f5b0994e30ff50959ff223c2a0b3784f4b8de31fa15c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d3eeb97361610675c2d46f79e1fdd84989d199a6 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "594c017a98d20582b453a9cad99c02d53e61877c433dc50069c0f2a6b6c683a1", + "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/d1deda1ebf791aa785d213b26e00362bca09dd9d/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "7e330b4fb14adac48e79964cf506b0f7067d5a3ff8ede49a321c92bb1997ee85", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "795855630f9230fbb6ef3e7ceb484d8fbc0339c0dbd9af51f0237ed82e1c152d", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__5wzhcy9r", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "61ec89c70c89b0546e9a633eeda224ac31cbf94f182b4b8a829858dc33d600ea", + "is_fork": true, + "learner_path": "tasks/f808044c40e0e9f7d468872f/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/d1deda1ebf791aa785d213b26e00362bca09dd9d/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": "5f9e78aae9222258ff7bcd1489bc728d7efe416d136f686fe212fef08ece2583", + "provenance_path": "tasks/f808044c40e0e9f7d468872f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d1deda1ebf791aa785d213b26e00362bca09dd9d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "56d33cb7871bf7281709be20e714c0a688f670ec", + "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__5wzhcy9r", + "task_sha256": "e9caf0c2de44efb002d0f5b0994e30ff50959ff223c2a0b3784f4b8de31fa15c", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..1f39c52b25e0f25b862ef5926714d25e1337b8c0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/provided-gold.diff @@ -0,0 +1,45 @@ +diff --git a/src/click/globals.py b/src/click/globals.py +index 57ef5e7a022a53d470837b4dcb9220448a4680cd..a2f91723d21cefdf658be327174e1f8ccdc20fcd 100644 +--- a/src/click/globals.py ++++ b/src/click/globals.py +@@ -33,17 +33,17 @@ + :exc:`RuntimeError`. + """ + try: +- return t.cast("Context", _local.stack[0]) +- except (AttributeError) as e: +- if silent: ++ return t.cast("Context", _local.stack[-1]) ++ except (AttributeError, IndexError) as e: ++ if not silent: + raise RuntimeError("There is no active click context.") from e + +- return Context() ++ return None + + + def push_context(ctx: Context) -> None: + """Pushes a new context to the current stack.""" +- _local.__dict__.setdefault("stack", []).insert(0, ctx) ++ _local.__dict__.setdefault("stack", []).append(ctx) + + + def pop_context() -> None: +@@ -56,12 +56,12 @@ + value is passed it's returned unchanged, otherwise it's looked up from + the current context. + """ +- if color is None: +- return False ++ if color is not None: ++ return color + +- ctx = get_current_context(silent=False) ++ ctx = get_current_context(silent=True) + + if ctx is not None: +- return not ctx.color ++ return ctx.color + +- return True ++ return None diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bc2b16f11955fb95576e12f4fc5abce6b5a2d325 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/solution/solve.sh @@ -0,0 +1,51 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/globals.py b/src/click/globals.py +index 57ef5e7a022a53d470837b4dcb9220448a4680cd..a2f91723d21cefdf658be327174e1f8ccdc20fcd 100644 +--- a/src/click/globals.py ++++ b/src/click/globals.py +@@ -33,17 +33,17 @@ + :exc:`RuntimeError`. + """ + try: +- return t.cast("Context", _local.stack[0]) +- except (AttributeError) as e: +- if silent: ++ return t.cast("Context", _local.stack[-1]) ++ except (AttributeError, IndexError) as e: ++ if not silent: + raise RuntimeError("There is no active click context.") from e + +- return Context() ++ return None + + + def push_context(ctx: Context) -> None: + """Pushes a new context to the current stack.""" +- _local.__dict__.setdefault("stack", []).insert(0, ctx) ++ _local.__dict__.setdefault("stack", []).append(ctx) + + + def pop_context() -> None: +@@ -56,12 +56,12 @@ + value is passed it's returned unchanged, otherwise it's looked up from + the current context. + """ +- if color is None: +- return False ++ if color is not None: ++ return color + +- ctx = get_current_context(silent=False) ++ ctx = get_current_context(silent=True) + + if ctx is not None: +- return not ctx.color ++ return ctx.color + +- return True ++ return None +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/task.toml b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..90426cdbfb69c8e7c42e38033127deecb86d1e97 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "fail-to-pass": [ + "tests/test_context.py::test_global_context_object", + "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_secho_non_text[123-\\x1b[45m123\\x1b[0m]", + "tests/test_termui.py::test_progressbar_yields_all_items", + "tests/test_termui.py::test_progress_bar_update_min_steps", + "tests/test_testing.py::test_with_color", + "tests/test_testing.py::test_with_color_errors", + "tests/test_utils.py::test_echo_color_flag" + ], + "pass-to-pass": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_context_meta", + "tests/test_context.py::test_make_pass_meta_decorator", + "tests/test_context.py::test_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_init_exceptions", + "tests/test_termui.py::test_progressbar_iter_outside_with_exceptions", + "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_secho", + "tests/test_termui.py::test_secho_non_text[test-test]", + "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_fast_edit", + "tests/test_termui.py::test_edit", + "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_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_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-00.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", + "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_prompts", + "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_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", + "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_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_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", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..fac56fb554837b29949d7257b6437709129e2c8e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/canaries/first-hunk-only.sh @@ -0,0 +1,33 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/globals.py b/src/click/globals.py +index 57ef5e7a022a53d470837b4dcb9220448a4680cd..a2f91723d21cefdf658be327174e1f8ccdc20fcd 100644 +--- a/src/click/globals.py ++++ b/src/click/globals.py +@@ -33,17 +33,17 @@ + :exc:`RuntimeError`. + """ + try: +- return t.cast("Context", _local.stack[0]) +- except (AttributeError) as e: +- if silent: ++ return t.cast("Context", _local.stack[-1]) ++ except (AttributeError, IndexError) as e: ++ if not silent: + raise RuntimeError("There is no active click context.") from e + +- return Context() ++ return None + + + def push_context(ctx: Context) -> None: + """Pushes a new context to the current stack.""" +- _local.__dict__.setdefault("stack", []).insert(0, ctx) ++ _local.__dict__.setdefault("stack", []).append(ctx) + + + def pop_context() -> None: +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__5wzhcy9r/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e4d07ecb3afbe1e3104db660547f5ca206ff8d16 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "af00bf3d9cd726fabdc246c21ccb95a9132dc9cb3a286cb852e7cc9e699eeea7", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "1c832931c5d53f9d80c2cb6d261283e808cee35cd27bb96b513e6627c606f405", + "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": "c905e7d6d19cef51de8536ae1eac8c88c8925301670e35c8b6517e5cce34056f", + "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": "9941e89b09c409a28395ce63b35d1db666c9a9bc", + "source_completion_sha256": "028f9b7afdb81c2ecf9de32e818666a8359d85db6e2be23bd46ff3bf053683eb", + "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__d0dbratz", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "7d40dbb0c47c5fbcebafec25d1d2b11fb7c9ff3b8ce32fe0c53ae9ca79bbbc0c", + "is_fork": true, + "learner_path": "tasks/7df6740b87609283b2e67fc2/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/9941e89b09c409a28395ce63b35d1db666c9a9bc/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": "b4fc75d324e375c744a2ddd7fa8376e05b3646bcc2177a022ba741b81ac3a8e9", + "provenance_path": "tasks/7df6740b87609283b2e67fc2/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9941e89b09c409a28395ce63b35d1db666c9a9bc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f2c1c21f226e88533186199d9b3e9c92262d994f", + "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__d0dbratz", + "task_sha256": "f1bf8c82b81d5dc8a74ccb9c9a8d78a40a01bc36cd4f566eef597c45f865ddf0", + "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__d0dbratz", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..462e72bec136d7502e1460bf2d7969ec8fd5ac58 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/instruction.md @@ -0,0 +1,29 @@ +Option processing broken - values and constants swapped + +When using Click options with different actions, the values are being processed incorrectly. Options that should store their provided values are instead storing constants, and options that should store constants are storing the provided values. + +#### Steps/Code to Reproduce + +```python +import click + +@click.command() +@click.option('--flag', is_flag=True) +@click.option('--value', default='default') +@click.option('--count', count=True) +def cli(flag, value, count): + click.echo(f'flag: {flag}') + click.echo(f'value: {value}') + click.echo(f'count: {count}') + +if __name__ == '__main__': + cli() +``` + +Running with `--value test --count --count` produces unexpected output where the value option doesn't get the provided value and the count option behaves incorrectly. + +Also affects options with `append` action and other option types. The issue seems to be in the option processing logic where values and constants are being mixed up. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..a06bc6d29347a194ce2f5ec5d03a0a703755c8b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/metadata.json @@ -0,0 +1,744 @@ +{ + "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_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_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_basic.py::test_basic_functionality", + "tests/test_basic.py::test_basic_group", + "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[args1-I:[46]]", + "tests/test_basic.py::test_uuid_option[args1-U:[821592c1-c50e-4971-9cd6-e89dc6832f86]]", + "tests/test_basic.py::test_float_option[--f=23.5-F:[23.5]]", + "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_flag[args0-True-True]", + "tests/test_basic.py::test_boolean_flag[args0-True-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_evaluation_order", + "tests/test_basic.py::test_hidden_command", + "tests/test_basic.py::test_hidden_group", + "tests/test_basic.py::test_summary_line", + "tests/test_basic.py::test_help_invalid_default", + "tests/test_chain.py::test_chaining_with_options", + "tests/test_chain.py::test_chaining_with_arguments", + "tests/test_chain.py::test_pipeline[args0-foo\\nbar-expect0]", + "tests/test_chain.py::test_group_arg_behavior", + "tests/test_command_decorators.py::test_params_argument", + "tests/test_commands.py::test_forwarded_params_consistency", + "tests/test_commands.py::test_auto_shorthelp", + "tests/test_commands.py::test_group_with_args[args2-0-obj=obj1\\nmove\\n]", + "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_context.py::test_no_state_leaks", + "tests/test_context.py::test_propagate_show_default_setting", + "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_global_show_default", + "tests/test_formatting.py::test_formatting_with_options_metavar_empty", + "tests/test_normalization.py::test_option_normalization", + "tests/test_normalization.py::test_choice_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_multiple_required", + "tests/test_options.py::test_multiple_default_help", + "tests/test_options.py::test_show_default_default_map", + "tests/test_options.py::test_dynamic_default_help_unset", + "tests/test_options.py::test_dynamic_default_help_text", + "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_winstyle_options", + "tests/test_options.py::test_legacy_options", + "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_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[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_multiple_option_with_optional_value", + "tests/test_shell_completion.py::test_command", + "tests/test_shell_completion.py::test_group_command_same_option", + "tests/test_shell_completion.py::test_argument_order", + "tests/test_shell_completion.py::test_argument_default", + "tests/test_shell_completion.py::test_option_optional", + "tests/test_shell_completion.py::test_option_flag", + "tests/test_shell_completion.py::test_option_custom", + "tests/test_shell_completion.py::test_argument_nargs", + "tests/test_shell_completion.py::test_double_dash", + "tests/test_shell_completion.py::test_context_settings", + "tests/test_testing.py::test_file_stdin_attrs", + "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_utils.py::test_open_file", + "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_bytes_args", + "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_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_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_repr", + "tests/test_basic.py::test_return_values", + "tests/test_basic.py::test_group_commands_dict", + "tests/test_basic.py::test_group_from_list", + "tests/test_basic.py::test_int_option[args0-I:[84]]", + "tests/test_basic.py::test_uuid_option[args0-U:[ba122011-349f-423b-873b-9d6a79c688ab]]", + "tests/test_basic.py::test_float_option[args0-F:[42.0]]", + "tests/test_basic.py::test_boolean_switch[args0-True-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[args1-False-True]", + "tests/test_basic.py::test_boolean_flag[args1-False-False]", + "tests/test_basic.py::test_required_option", + "tests/test_basic.py::test_hidden_option", + "tests/test_chain.py::test_basic_chaining", + "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_args_and_chain", + "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_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_command_no_args_is_help", + "tests/test_commands.py::test_default_maps", + "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_group_add_command_name", + "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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_formatting.py::test_removing_multiline_marker", + "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_normalization.py::test_command_normalization", + "tests/test_options.py::test_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "tests/test_options.py::test_unknown_options[--foo]", + "tests/test_options.py::test_unknown_options[-f]", + "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_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_type", + "tests/test_options.py::test_multiple_default_composite_type", + "tests/test_options.py::test_parse_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=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_toupper_envvar_prefix", + "tests/test_options.py::test_nargs_envvar", + "tests/test_options.py::test_callback_validates_prompt", + "tests/test_options.py::test_missing_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "tests/test_options.py::test_bool_flag_with_type", + "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_option_with_optional_value[args9-expect9]", + "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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "tests/test_parser.py::test_parser_default_prefixes", + "tests/test_parser.py::test_parser_collects_prefixes", + "tests/test_shell_completion.py::test_group", + "tests/test_shell_completion.py::test_chained", + "tests/test_shell_completion.py::test_help_option", + "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_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_multiple", + "tests/test_shell_completion.py::test_option_nargs", + "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_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_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_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_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_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_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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_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-00.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_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", + "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_prompts", + "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_pathlib_dash", + "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": "f2c1c21f226e88533186199d9b3e9c92262d994f", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "9941e89b09c409a28395ce63b35d1db666c9a9bc" + }, + "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_custom_classes.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_termui.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_defaults.py", + "tests/test_formatting.py", + "tests/test_normalization.py", + "tests/test_options.py", + "tests/test_shell_completion.py", + "tests/test_testing.py", + "tests/test_types.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/parser.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2684890, + "task_id": "pallets__click.fde47b4b.combine_file__d0dbratz", + "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__d0dbratz", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "7d40dbb0c47c5fbcebafec25d1d2b11fb7c9ff3b8ce32fe0c53ae9ca79bbbc0c", + "is_fork": true, + "learner_path": "tasks/7df6740b87609283b2e67fc2/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/9941e89b09c409a28395ce63b35d1db666c9a9bc/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": "b4fc75d324e375c744a2ddd7fa8376e05b3646bcc2177a022ba741b81ac3a8e9", + "provenance_path": "tasks/7df6740b87609283b2e67fc2/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9941e89b09c409a28395ce63b35d1db666c9a9bc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f2c1c21f226e88533186199d9b3e9c92262d994f", + "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__d0dbratz", + "task_sha256": "f1bf8c82b81d5dc8a74ccb9c9a8d78a40a01bc36cd4f566eef597c45f865ddf0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..539a44ba50e1625403b1a3f36ff878cc6e36f8cc --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "af00bf3d9cd726fabdc246c21ccb95a9132dc9cb3a286cb852e7cc9e699eeea7", + "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/9941e89b09c409a28395ce63b35d1db666c9a9bc/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "028f9b7afdb81c2ecf9de32e818666a8359d85db6e2be23bd46ff3bf053683eb", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "ae916719deddb70ecd1fe90e0189d313d80ead04b0cbdcff165bbedce69ea574", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__d0dbratz", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "7d40dbb0c47c5fbcebafec25d1d2b11fb7c9ff3b8ce32fe0c53ae9ca79bbbc0c", + "is_fork": true, + "learner_path": "tasks/7df6740b87609283b2e67fc2/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/9941e89b09c409a28395ce63b35d1db666c9a9bc/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": "b4fc75d324e375c744a2ddd7fa8376e05b3646bcc2177a022ba741b81ac3a8e9", + "provenance_path": "tasks/7df6740b87609283b2e67fc2/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9941e89b09c409a28395ce63b35d1db666c9a9bc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f2c1c21f226e88533186199d9b3e9c92262d994f", + "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__d0dbratz", + "task_sha256": "f1bf8c82b81d5dc8a74ccb9c9a8d78a40a01bc36cd4f566eef597c45f865ddf0", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a1e0c0904567b9f077fc60dc0844e78bf97673c7 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/provided-gold.diff @@ -0,0 +1,63 @@ +diff --git a/src/click/parser.py b/src/click/parser.py +index 21965beaf587f97833f9112b592733bf9234eee0..a8b7d2634a89df3c9e0b7a1f85dfd4bace60a608 100644 +--- a/src/click/parser.py ++++ b/src/click/parser.py +@@ -165,18 +165,18 @@ + + def process(self, value: t.Any, state: _ParsingState) -> None: + if self.action == "store": ++ state.opts[self.dest] = value # type: ignore ++ elif self.action == "store_const": + state.opts[self.dest] = self.const # type: ignore +- elif self.action == "store_const": +- state.opts[self.dest] = value # type: ignore + elif self.action == "append": ++ state.opts.setdefault(self.dest, []).append(value) # type: ignore ++ elif self.action == "append_const": + state.opts.setdefault(self.dest, []).append(self.const) # type: ignore +- elif self.action == "append_const": +- state.opts.setdefault(self.dest, []).append(value) # type: ignore + elif self.action == "count": +- state.opts[self.dest] = state.opts.get(self.dest, 0) - 1 # type: ignore ++ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore + else: + raise ValueError(f"unknown action '{self.action}'") +- state.order.insert(0, self.obj) ++ state.order.append(self.obj) + + + class _Argument: +@@ -190,23 +190,25 @@ + value: str | cabc.Sequence[str | None] | None, + state: _ParsingState, + ) -> None: +- if self.nargs >= 1: ++ if self.nargs > 1: + assert value is not None + holes = sum(1 for x in value if x is None) +- if holes == len(value) - 1: ++ if holes == len(value): + value = None +- elif holes == 0: ++ elif holes != 0: + raise BadArgumentUsage( + _("Argument {name!r} takes {nargs} values.").format( + name=self.dest, nargs=self.nargs + ) + ) + +- if self.nargs == -1 and self.obj.envvar is None and value == (): +- value = "" +- +- state.opts[self.dest] = value +- state.order.insert(0, self.obj) ++ if self.nargs == -1 and self.obj.envvar is not None and value == (): ++ # Replace empty tuple with None so that a value from the ++ # environment may be tried. ++ value = None ++ ++ state.opts[self.dest] = value # type: ignore ++ state.order.append(self.obj) + + + class _ParsingState: diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..75dfbedaef455c65d9d12cc4ad3ff75519d19b58 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/solution/solve.sh @@ -0,0 +1,69 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/parser.py b/src/click/parser.py +index 21965beaf587f97833f9112b592733bf9234eee0..a8b7d2634a89df3c9e0b7a1f85dfd4bace60a608 100644 +--- a/src/click/parser.py ++++ b/src/click/parser.py +@@ -165,18 +165,18 @@ + + def process(self, value: t.Any, state: _ParsingState) -> None: + if self.action == "store": ++ state.opts[self.dest] = value # type: ignore ++ elif self.action == "store_const": + state.opts[self.dest] = self.const # type: ignore +- elif self.action == "store_const": +- state.opts[self.dest] = value # type: ignore + elif self.action == "append": ++ state.opts.setdefault(self.dest, []).append(value) # type: ignore ++ elif self.action == "append_const": + state.opts.setdefault(self.dest, []).append(self.const) # type: ignore +- elif self.action == "append_const": +- state.opts.setdefault(self.dest, []).append(value) # type: ignore + elif self.action == "count": +- state.opts[self.dest] = state.opts.get(self.dest, 0) - 1 # type: ignore ++ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore + else: + raise ValueError(f"unknown action '{self.action}'") +- state.order.insert(0, self.obj) ++ state.order.append(self.obj) + + + class _Argument: +@@ -190,23 +190,25 @@ + value: str | cabc.Sequence[str | None] | None, + state: _ParsingState, + ) -> None: +- if self.nargs >= 1: ++ if self.nargs > 1: + assert value is not None + holes = sum(1 for x in value if x is None) +- if holes == len(value) - 1: ++ if holes == len(value): + value = None +- elif holes == 0: ++ elif holes != 0: + raise BadArgumentUsage( + _("Argument {name!r} takes {nargs} values.").format( + name=self.dest, nargs=self.nargs + ) + ) + +- if self.nargs == -1 and self.obj.envvar is None and value == (): +- value = "" +- +- state.opts[self.dest] = value +- state.order.insert(0, self.obj) ++ if self.nargs == -1 and self.obj.envvar is not None and value == (): ++ # Replace empty tuple with None so that a value from the ++ # environment may be tried. ++ value = None ++ ++ state.opts[self.dest] = value # type: ignore ++ state.order.append(self.obj) + + + class _ParsingState: +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/task.toml b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..a158dba096b9530080ced327219276afac46b956 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "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_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_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_basic.py::test_basic_functionality", + "tests/test_basic.py::test_basic_group", + "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[args1-I:[46]]", + "tests/test_basic.py::test_uuid_option[args1-U:[821592c1-c50e-4971-9cd6-e89dc6832f86]]", + "tests/test_basic.py::test_float_option[--f=23.5-F:[23.5]]", + "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_flag[args0-True-True]", + "tests/test_basic.py::test_boolean_flag[args0-True-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_evaluation_order", + "tests/test_basic.py::test_hidden_command", + "tests/test_basic.py::test_hidden_group", + "tests/test_basic.py::test_summary_line", + "tests/test_basic.py::test_help_invalid_default", + "tests/test_chain.py::test_chaining_with_options", + "tests/test_chain.py::test_chaining_with_arguments", + "tests/test_chain.py::test_pipeline[args0-foo\\nbar-expect0]", + "tests/test_chain.py::test_group_arg_behavior", + "tests/test_command_decorators.py::test_params_argument", + "tests/test_commands.py::test_forwarded_params_consistency", + "tests/test_commands.py::test_auto_shorthelp", + "tests/test_commands.py::test_group_with_args[args2-0-obj=obj1\\nmove\\n]", + "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_context.py::test_no_state_leaks", + "tests/test_context.py::test_propagate_show_default_setting", + "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_global_show_default", + "tests/test_formatting.py::test_formatting_with_options_metavar_empty", + "tests/test_normalization.py::test_option_normalization", + "tests/test_normalization.py::test_choice_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_multiple_required", + "tests/test_options.py::test_multiple_default_help", + "tests/test_options.py::test_show_default_default_map", + "tests/test_options.py::test_dynamic_default_help_unset", + "tests/test_options.py::test_dynamic_default_help_text", + "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_winstyle_options", + "tests/test_options.py::test_legacy_options", + "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_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[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_multiple_option_with_optional_value", + "tests/test_shell_completion.py::test_command", + "tests/test_shell_completion.py::test_group_command_same_option", + "tests/test_shell_completion.py::test_argument_order", + "tests/test_shell_completion.py::test_argument_default", + "tests/test_shell_completion.py::test_option_optional", + "tests/test_shell_completion.py::test_option_flag", + "tests/test_shell_completion.py::test_option_custom", + "tests/test_shell_completion.py::test_argument_nargs", + "tests/test_shell_completion.py::test_double_dash", + "tests/test_shell_completion.py::test_context_settings", + "tests/test_testing.py::test_file_stdin_attrs", + "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_utils.py::test_open_file", + "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_bytes_args", + "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_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_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_repr", + "tests/test_basic.py::test_return_values", + "tests/test_basic.py::test_group_commands_dict", + "tests/test_basic.py::test_group_from_list", + "tests/test_basic.py::test_int_option[args0-I:[84]]", + "tests/test_basic.py::test_uuid_option[args0-U:[ba122011-349f-423b-873b-9d6a79c688ab]]", + "tests/test_basic.py::test_float_option[args0-F:[42.0]]", + "tests/test_basic.py::test_boolean_switch[args0-True-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[args1-False-True]", + "tests/test_basic.py::test_boolean_flag[args1-False-False]", + "tests/test_basic.py::test_required_option", + "tests/test_basic.py::test_hidden_option", + "tests/test_chain.py::test_basic_chaining", + "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_args_and_chain", + "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_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_command_no_args_is_help", + "tests/test_commands.py::test_default_maps", + "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_group_add_command_name", + "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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_formatting.py::test_removing_multiline_marker", + "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_normalization.py::test_command_normalization", + "tests/test_options.py::test_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "tests/test_options.py::test_unknown_options[--foo]", + "tests/test_options.py::test_unknown_options[-f]", + "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_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_type", + "tests/test_options.py::test_multiple_default_composite_type", + "tests/test_options.py::test_parse_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=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_toupper_envvar_prefix", + "tests/test_options.py::test_nargs_envvar", + "tests/test_options.py::test_callback_validates_prompt", + "tests/test_options.py::test_missing_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "tests/test_options.py::test_bool_flag_with_type", + "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_option_with_optional_value[args9-expect9]", + "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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "tests/test_parser.py::test_parser_default_prefixes", + "tests/test_parser.py::test_parser_collects_prefixes", + "tests/test_shell_completion.py::test_group", + "tests/test_shell_completion.py::test_chained", + "tests/test_shell_completion.py::test_help_option", + "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_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_multiple", + "tests/test_shell_completion.py::test_option_nargs", + "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_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_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_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_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_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_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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_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-00.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_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", + "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_prompts", + "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_pathlib_dash", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..989ef2c02dffa8d6eb1770507f639f752f2315e9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/canaries/first-hunk-only.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/parser.py b/src/click/parser.py +index 21965beaf587f97833f9112b592733bf9234eee0..a8b7d2634a89df3c9e0b7a1f85dfd4bace60a608 100644 +--- a/src/click/parser.py ++++ b/src/click/parser.py +@@ -165,18 +165,18 @@ + + def process(self, value: t.Any, state: _ParsingState) -> None: + if self.action == "store": ++ state.opts[self.dest] = value # type: ignore ++ elif self.action == "store_const": + state.opts[self.dest] = self.const # type: ignore +- elif self.action == "store_const": +- state.opts[self.dest] = value # type: ignore + elif self.action == "append": ++ state.opts.setdefault(self.dest, []).append(value) # type: ignore ++ elif self.action == "append_const": + state.opts.setdefault(self.dest, []).append(self.const) # type: ignore +- elif self.action == "append_const": +- state.opts.setdefault(self.dest, []).append(value) # type: ignore + elif self.action == "count": +- state.opts[self.dest] = state.opts.get(self.dest, 0) - 1 # type: ignore ++ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore + else: + raise ValueError(f"unknown action '{self.action}'") +- state.order.insert(0, self.obj) ++ state.order.append(self.obj) + + + class _Argument: +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__d0dbratz/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..654e558c502c26c2977283d1128e8722caeae023 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "cbb3a254e0a10506ebb96ff6f7b958a334f53fe4f397e30bd8f06900af682235", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "55d55279283a60557a0022626b95e1bf4fe1244161b57e5896b2b6fb85458caa", + "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": "dfe55bd0ab04799dd442451c048034791cf7299d52c37588cb495b6a29f88d5c", + "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": "096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c", + "source_completion_sha256": "22ba5bf494c8e2a5ab163c77c04e7683d8aafeb6d8c462f039119dd0b8611063", + "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__i7xmejm5", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "581b04391c2a26ad90e042d4b275d923eb3ad8864ddbedb3d8d1666bb80d69eb", + "is_fork": true, + "learner_path": "tasks/b575b9639019d8ed42ea1e00/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/096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c/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": "e87ff04025f4567fc12d84295dc8dde55886ad850d082f62751d7737e12f8ec0", + "provenance_path": "tasks/b575b9639019d8ed42ea1e00/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "18ba5bac1db624d1d97f22f671d863dffe458ed7", + "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__i7xmejm5", + "task_sha256": "d7acafa888dd50b8016453c7eb9cb66d557cc8d589611b17d6156edfd28cc4e1", + "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__i7xmejm5", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee2d07e42b2b9e523ee34da40ec4bcdd4664d4cd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/instruction.md @@ -0,0 +1,69 @@ +# Prompts not displaying correctly in CliRunner + +### Bug description + +I'm using the CliRunner to test my Click commands that use prompts, but I've noticed that the prompts are not displaying correctly. + +When using the `hidden_input` function in the CliRunner, it's adding a newline after the prompt text, which makes the output look wrong. Also, when reading input, it's using `rstrip("\r\n")` which removes trailing whitespace differently than expected. + +### Command used + +```python +@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') +``` + +### Output + +The output shows the prompt with a newline after it, which doesn't match how prompts normally appear in a terminal: + +``` +Foo: +wau wau +foo=wau wau +``` + +### Expected behavior + +The prompt should appear on the same line as the input, like this: + +``` +Foo: wau wau +foo=wau wau +``` + +This also affects commands that use Python's built-in `input()` function when tested with CliRunner. + +### Environment + +Click version: latest +Python 3.10 + +### Reproduction + +Here's a simple script to reproduce the issue: + +```python +import click +from click.testing import CliRunner + +@click.command() +@click.option('--name', prompt=True) +def hello(name): + click.echo(f"Hello {name}!") + +runner = CliRunner() +result = runner.invoke(hello, input="World\n") +print(result.output) +``` + +The output will show the prompt on a separate line from the input, which is not how it would appear in a real terminal. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..656898919dd31c66e6fc1b8d8edacec828e8c435 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/metadata.json @@ -0,0 +1,744 @@ +{ + "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_commands.py::test_aliased_command_canonical_name", + "tests/test_testing.py::test_echo_stdin_prompts", + "tests/test_testing.py::test_prompts" + ], + "PASS_TO_PASS": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_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_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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_runner_with_stream", + "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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "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": "18ba5bac1db624d1d97f22f671d863dffe458ed7", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c" + }, + "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_arguments.py", + "/testbed/tests/test_basic.py", + "/testbed/tests/test_chain.py", + "/testbed/tests/test_command_decorators.py", + "/testbed/tests/test_compat.py", + "/testbed/tests/test_context.py", + "/testbed/tests/test_custom_classes.py", + "/testbed/tests/test_defaults.py", + "/testbed/tests/test_formatting.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_normalization.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_shell_completion.py", + "/testbed/tests/test_termui.py", + "/testbed/tests/test_types.py", + "/testbed/tests/test_utils.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_commands.py", + "tests/test_testing.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/testing.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2823118, + "task_id": "pallets__click.fde47b4b.combine_file__i7xmejm5", + "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__i7xmejm5", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "581b04391c2a26ad90e042d4b275d923eb3ad8864ddbedb3d8d1666bb80d69eb", + "is_fork": true, + "learner_path": "tasks/b575b9639019d8ed42ea1e00/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/096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c/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": "e87ff04025f4567fc12d84295dc8dde55886ad850d082f62751d7737e12f8ec0", + "provenance_path": "tasks/b575b9639019d8ed42ea1e00/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "18ba5bac1db624d1d97f22f671d863dffe458ed7", + "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__i7xmejm5", + "task_sha256": "d7acafa888dd50b8016453c7eb9cb66d557cc8d589611b17d6156edfd28cc4e1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..2c3cf1457dcef739b147aaeb57ddab87c4b7ea0d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "cbb3a254e0a10506ebb96ff6f7b958a334f53fe4f397e30bd8f06900af682235", + "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/096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "22ba5bf494c8e2a5ab163c77c04e7683d8aafeb6d8c462f039119dd0b8611063", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "2a2c92cb2cf0ead3c0bb90717ec9a062c796ab3e646bce85ca8f4ef22ec5d998", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__i7xmejm5", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "581b04391c2a26ad90e042d4b275d923eb3ad8864ddbedb3d8d1666bb80d69eb", + "is_fork": true, + "learner_path": "tasks/b575b9639019d8ed42ea1e00/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/096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c/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": "e87ff04025f4567fc12d84295dc8dde55886ad850d082f62751d7737e12f8ec0", + "provenance_path": "tasks/b575b9639019d8ed42ea1e00/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "096e9b104380e459bfc86ac3f6d3cd4cfcd27e8c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "18ba5bac1db624d1d97f22f671d863dffe458ed7", + "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__i7xmejm5", + "task_sha256": "d7acafa888dd50b8016453c7eb9cb66d557cc8d589611b17d6156edfd28cc4e1", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..342736e14c503122cf22cad62629c7e775d8d704 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/provided-gold.diff @@ -0,0 +1,25 @@ +diff --git a/src/click/testing.py b/src/click/testing.py +index c568052848379aac5030d610596d8940202cf2b3..73462dbd03e3d40d4fefd76b4d7337ebd88713c4 100644 +--- a/src/click/testing.py ++++ b/src/click/testing.py +@@ -247,7 +247,7 @@ + for it. The default is the `name` attribute or ``"root"`` if not + set. + """ +- return cli.name if cli.name is not None else "main" ++ return cli.name or "root" + + def make_env( + self, overrides: cabc.Mapping[str, str | None] | None = None +@@ -341,9 +341,9 @@ + + @_pause_echo(echo_input) # type: ignore + def hidden_input(prompt: str | None = None) -> str: +- sys.stdout.write(f"{prompt or ''}") ++ sys.stdout.write(f"{prompt or ''}\n") + sys.stdout.flush() +- return text_input.readline().strip("\n") ++ return text_input.readline().rstrip("\r\n") + + @_pause_echo(echo_input) # type: ignore + def _getchar(echo: bool) -> str: diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6058c765cf2fde18794366ad35033d50d331b39 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/solution/solve.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/testing.py b/src/click/testing.py +index c568052848379aac5030d610596d8940202cf2b3..73462dbd03e3d40d4fefd76b4d7337ebd88713c4 100644 +--- a/src/click/testing.py ++++ b/src/click/testing.py +@@ -247,7 +247,7 @@ + for it. The default is the `name` attribute or ``"root"`` if not + set. + """ +- return cli.name if cli.name is not None else "main" ++ return cli.name or "root" + + def make_env( + self, overrides: cabc.Mapping[str, str | None] | None = None +@@ -341,9 +341,9 @@ + + @_pause_echo(echo_input) # type: ignore + def hidden_input(prompt: str | None = None) -> str: +- sys.stdout.write(f"{prompt or ''}") ++ sys.stdout.write(f"{prompt or ''}\n") + sys.stdout.flush() +- return text_input.readline().strip("\n") ++ return text_input.readline().rstrip("\r\n") + + @_pause_echo(echo_input) # type: ignore + def _getchar(echo: bool) -> str: +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/task.toml b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..fa5abb39d42ae35dfd8bfe811ad199ad3ccbb038 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "fail-to-pass": [ + "tests/test_commands.py::test_aliased_command_canonical_name", + "tests/test_testing.py::test_echo_stdin_prompts", + "tests/test_testing.py::test_prompts" + ], + "pass-to-pass": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_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_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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_runner_with_stream", + "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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..66cdf8f4066eeadf85b45e2916977f932dc74643 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/testing.py b/src/click/testing.py +index c568052848379aac5030d610596d8940202cf2b3..73462dbd03e3d40d4fefd76b4d7337ebd88713c4 100644 +--- a/src/click/testing.py ++++ b/src/click/testing.py +@@ -247,7 +247,7 @@ + for it. The default is the `name` attribute or ``"root"`` if not + set. + """ +- return cli.name if cli.name is not None else "main" ++ return cli.name or "root" + + def make_env( + self, overrides: cabc.Mapping[str, str | None] | None = None +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__i7xmejm5/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__k328265n/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__k328265n/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..c086fa9a3e3a4ec6601689f0b990da329a6bca94 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "f70d6d15fe8fd90ce861451ee1433c46c39fbe4c7badd8217e8ffc92f4cc464d", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "707e067f50d629ecad0baefb44ac293f66e4ad13a66fb6a1842959321359d439", + "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": "ec6c1bd5efaefa0b39f466889360a164381950ec07669be26229f3a351ce6e3c", + "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": "4729f912792d86a31a3060bff53901427e7624e7", + "source_completion_sha256": "b15776977d8e230345daaae28c83f7ce56ea68322e73362539684a8dbe3579f0", + "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__k328265n", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "234339ed7544c68c8cac5fc3156d1bbf4356d2e876e0985af12c9ad35365c918", + "is_fork": true, + "learner_path": "tasks/9f24fc16bde9931214518265/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/4729f912792d86a31a3060bff53901427e7624e7/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": "872c183a04423300a83d93971eb4d20a9f4dad235a0b27bf9455b5b456372828", + "provenance_path": "tasks/9f24fc16bde9931214518265/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4729f912792d86a31a3060bff53901427e7624e7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e000e11d78af6fdee21295647d2a972058125c57", + "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__k328265n", + "task_sha256": "350a7fb2c2e9bec9a065fbe7f04e78663199e715741106805365bffada4372be", + "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__k328265n", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__k328265n/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__k328265n/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__k328265n/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d20fca6f2d740dcce9ee8a32cce7d6915b8cabef --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/instruction.md @@ -0,0 +1,31 @@ +Parameter processing order broken for eager options + +#### Description + +When using eager options in Click commands, the parameter processing order is incorrect. Eager options should be processed first, but they're being processed last instead. + +#### Steps/Code to Reproduce + +```python +import click + +@click.command() +@click.option('--verbose', '-v', is_flag=True, is_eager=True) +@click.option('--help', is_flag=True, expose_value=False, is_eager=True) +@click.option('--name', default='world') +def hello(verbose, name): + if verbose: + click.echo('Verbose mode enabled') + click.echo(f'Hello {name}!') + +if __name__ == '__main__': + hello() +``` + +When running with `--help`, the help option should be processed first due to being eager, but instead it gets processed after other parameters. This breaks the expected behavior where eager parameters like `--help` should take precedence and be handled before any other parameter processing occurs. + +The issue appears to affect the parameter processing order in commands where eager options should be prioritized but are instead being deprioritized in the processing queue. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__k328265n/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9e30efcaebe2ca48ffce6c8abc92b271b056763d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/metadata.json @@ -0,0 +1,744 @@ +{ + "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[-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_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_basic.py::test_basic_functionality", + "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_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_basic.py::test_help_invalid_default", + "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_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_command_no_args_is_help", + "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_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_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_propagate_show_default_setting", + "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_context_formatter_class", + "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_nested", + "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_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_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_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=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_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_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_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_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_multiple_option_with_optional_value", + "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_is_iterator", + "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_update_with_item_show_func", + "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_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_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_utils.py::test_echo", + "tests/test_utils.py::test_prompts", + "tests/test_utils.py::test_open_file", + "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_nargs_envvar[2--None]", + "tests/test_arguments.py::test_missing_arg", + "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_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_repr", + "tests/test_basic.py::test_required_option", + "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_group_add_command_name", + "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_compat.py::test_is_jupyter_kernel_output", + "tests/test_context.py::test_make_pass_meta_decorator_doc", + "tests/test_context.py::test_context_pushing", + "tests/test_context.py::test_with_resource", + "tests/test_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "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_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_no_help", + "tests/test_formatting.py::test_formatting_usage_custom_help", + "tests/test_formatting.py::test_removing_multiline_marker", + "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_unknown_options[--foo]", + "tests/test_options.py::test_unknown_options[-f]", + "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_missing_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "tests/test_options.py::test_flag_duplicate_names", + "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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_shell_completion.py::test_files_closed", + "tests/test_termui.py::test_progressbar_hidden_manual", + "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_choices_list_in_prompt", + "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_progressbar_item_show_func", + "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_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_false_show_default_cause_no_default_display_in_prompt", + "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-00.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_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_pathlib_dash", + "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": "e000e11d78af6fdee21295647d2a972058125c57", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "4729f912792d86a31a3060bff53901427e7624e7" + }, + "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_shell_completion.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_termui.py", + "tests/test_testing.py", + "tests/test_types.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/core.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2681585, + "task_id": "pallets__click.fde47b4b.combine_file__k328265n", + "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__k328265n", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "234339ed7544c68c8cac5fc3156d1bbf4356d2e876e0985af12c9ad35365c918", + "is_fork": true, + "learner_path": "tasks/9f24fc16bde9931214518265/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/4729f912792d86a31a3060bff53901427e7624e7/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": "872c183a04423300a83d93971eb4d20a9f4dad235a0b27bf9455b5b456372828", + "provenance_path": "tasks/9f24fc16bde9931214518265/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4729f912792d86a31a3060bff53901427e7624e7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e000e11d78af6fdee21295647d2a972058125c57", + "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__k328265n", + "task_sha256": "350a7fb2c2e9bec9a065fbe7f04e78663199e715741106805365bffada4372be", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__k328265n/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..43b2159a90b0d33a5cca1e3026e82b19f309df33 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "f70d6d15fe8fd90ce861451ee1433c46c39fbe4c7badd8217e8ffc92f4cc464d", + "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/4729f912792d86a31a3060bff53901427e7624e7/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b15776977d8e230345daaae28c83f7ce56ea68322e73362539684a8dbe3579f0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "e8aebd297056ab33f55c54edd0c49450728580f7943e998dbf091282da3dd4cd", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__k328265n", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "234339ed7544c68c8cac5fc3156d1bbf4356d2e876e0985af12c9ad35365c918", + "is_fork": true, + "learner_path": "tasks/9f24fc16bde9931214518265/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/4729f912792d86a31a3060bff53901427e7624e7/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": "872c183a04423300a83d93971eb4d20a9f4dad235a0b27bf9455b5b456372828", + "provenance_path": "tasks/9f24fc16bde9931214518265/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4729f912792d86a31a3060bff53901427e7624e7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e000e11d78af6fdee21295647d2a972058125c57", + "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__k328265n", + "task_sha256": "350a7fb2c2e9bec9a065fbe7f04e78663199e715741106805365bffada4372be", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__k328265n/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..46cd11766d5db9f042e6bb3e189e061930fd961f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/provided-gold.diff @@ -0,0 +1,655 @@ +diff --git a/src/click/core.py b/src/click/core.py +index 8943123d5dc860b236e175773722c8c38004b736..abe9fa9bb2bd9179031f5963749b36697309fbc1 100644 +--- a/src/click/core.py ++++ b/src/click/core.py +@@ -125,9 +125,9 @@ + try: + idx: float = invocation_order.index(item) + except ValueError: +- idx = float("-inf") +- +- return item.is_eager, idx ++ idx = float("inf") ++ ++ return not item.is_eager, idx + + return sorted(declaration_order, key=sort_key) + +@@ -262,59 +262,6 @@ + #: .. versionadded:: 8.0 + formatter_class: type[HelpFormatter] = HelpFormatter + +- @t.overload +- def invoke( +- self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any +- ) -> V: ... +- +- def __exit__( +- self, +- exc_type: type[BaseException] | None, +- exc_value: BaseException | None, +- tb: TracebackType | None, +- ) -> None: +- self._depth -= 1 +- if self._depth == 0: +- self.close() +- pop_context() +- +- @property +- def protected_args(self) -> list[str]: +- import warnings +- +- warnings.warn( +- "'protected_args' is deprecated and will be removed in Click 9.0." +- " 'args' will contain remaining unparsed tokens.", +- DeprecationWarning, +- stacklevel=2, +- ) +- return self._protected_args +- +- def find_object(self, object_type: type[V]) -> V | None: +- """Finds the closest object of a given type.""" +- node: Context | None = self +- +- while node is not None: +- if isinstance(node.obj, object_type): +- return node.obj +- +- node = node.parent +- +- return None +- +- def fail(self, message: str) -> t.NoReturn: +- """Aborts the execution of the program with a specific error +- message. +- +- :param message: the error message to fail with. +- """ +- raise UsageError(message, self) +- +- @t.overload +- def lookup_default( +- self, name: str, call: t.Literal[False] = ... +- ) -> t.Any | t.Callable[[], t.Any] | None: ... +- + def __init__( + self, + command: Command, +@@ -485,19 +432,54 @@ + self._parameter_source: dict[str, ParameterSource] = {} + self._exit_stack = ExitStack() + +- def ensure_object(self, object_type: type[V]) -> V: +- """Like :meth:`find_object` but sets the innermost object to a +- new instance of `object_type` if it does not exist. +- """ +- rv = self.find_object(object_type) +- if rv is None: +- self.obj = rv = object_type() +- return rv ++ @property ++ def protected_args(self) -> list[str]: ++ import warnings ++ ++ warnings.warn( ++ "'protected_args' is deprecated and will be removed in Click 9.0." ++ " 'args' will contain remaining unparsed tokens.", ++ DeprecationWarning, ++ stacklevel=2, ++ ) ++ return self._protected_args ++ ++ def to_info_dict(self) -> dict[str, t.Any]: ++ """Gather information that could be useful for a tool generating ++ user-facing documentation. This traverses the entire CLI ++ structure. ++ ++ .. code-block:: python ++ ++ with Context(cli) as ctx: ++ info = ctx.to_info_dict() ++ ++ .. versionadded:: 8.0 ++ """ ++ return { ++ "command": self.command.to_info_dict(self), ++ "info_name": self.info_name, ++ "allow_extra_args": self.allow_extra_args, ++ "allow_interspersed_args": self.allow_interspersed_args, ++ "ignore_unknown_options": self.ignore_unknown_options, ++ "auto_envvar_prefix": self.auto_envvar_prefix, ++ } + + def __enter__(self) -> Context: + self._depth += 1 + push_context(self) + return self ++ ++ def __exit__( ++ self, ++ exc_type: type[BaseException] | None, ++ exc_value: BaseException | None, ++ tb: TracebackType | None, ++ ) -> None: ++ self._depth -= 1 ++ if self._depth == 0: ++ self.close() ++ pop_context() + + @contextmanager + def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]: +@@ -537,17 +519,224 @@ + if not cleanup: + self._depth -= 1 + ++ @property ++ def meta(self) -> dict[str, t.Any]: ++ """This is a dictionary which is shared with all the contexts ++ that are nested. It exists so that click utilities can store some ++ state here if they need to. It is however the responsibility of ++ that code to manage this dictionary well. ++ ++ The keys are supposed to be unique dotted strings. For instance ++ module paths are a good choice for it. What is stored in there is ++ irrelevant for the operation of click. However what is important is ++ that code that places data here adheres to the general semantics of ++ the system. ++ ++ Example usage:: ++ ++ LANG_KEY = f'{__name__}.lang' ++ ++ def set_language(value): ++ ctx = get_current_context() ++ ctx.meta[LANG_KEY] = value ++ ++ def get_language(): ++ return get_current_context().meta.get(LANG_KEY, 'en_US') ++ ++ .. versionadded:: 5.0 ++ """ ++ return self._meta ++ ++ def make_formatter(self) -> HelpFormatter: ++ """Creates the :class:`~click.HelpFormatter` for the help and ++ usage output. ++ ++ To quickly customize the formatter class used without overriding ++ this method, set the :attr:`formatter_class` attribute. ++ ++ .. versionchanged:: 8.0 ++ Added the :attr:`formatter_class` attribute. ++ """ ++ return self.formatter_class( ++ width=self.terminal_width, max_width=self.max_content_width ++ ) ++ ++ def with_resource(self, context_manager: AbstractContextManager[V]) -> V: ++ """Register a resource as if it were used in a ``with`` ++ statement. The resource will be cleaned up when the context is ++ popped. ++ ++ Uses :meth:`contextlib.ExitStack.enter_context`. It calls the ++ resource's ``__enter__()`` method and returns the result. When ++ the context is popped, it closes the stack, which calls the ++ resource's ``__exit__()`` method. ++ ++ To register a cleanup function for something that isn't a ++ context manager, use :meth:`call_on_close`. Or use something ++ from :mod:`contextlib` to turn it into a context manager first. ++ ++ .. code-block:: python ++ ++ @click.group() ++ @click.option("--name") ++ @click.pass_context ++ def cli(ctx): ++ ctx.obj = ctx.with_resource(connect_db(name)) ++ ++ :param context_manager: The context manager to enter. ++ :return: Whatever ``context_manager.__enter__()`` returns. ++ ++ .. versionadded:: 8.0 ++ """ ++ return self._exit_stack.enter_context(context_manager) ++ ++ def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: ++ """Register a function to be called when the context tears down. ++ ++ This can be used to close resources opened during the script ++ execution. Resources that support Python's context manager ++ protocol which would be used in a ``with`` statement should be ++ registered with :meth:`with_resource` instead. ++ ++ :param f: The function to execute on teardown. ++ """ ++ return self._exit_stack.callback(f) ++ ++ def close(self) -> None: ++ """Invoke all close callbacks registered with ++ :meth:`call_on_close`, and exit all context managers entered ++ with :meth:`with_resource`. ++ """ ++ self._exit_stack.close() ++ # In case the context is reused, create a new exit stack. ++ self._exit_stack = ExitStack() ++ ++ @property ++ def command_path(self) -> str: ++ """The computed command path. This is used for the ``usage`` ++ information on the help page. It's automatically created by ++ combining the info names of the chain of contexts to the root. ++ """ ++ rv = "" ++ if self.info_name is not None: ++ rv = self.info_name ++ if self.parent is not None: ++ parent_command_path = [self.parent.command_path] ++ ++ if isinstance(self.parent.command, Command): ++ for param in self.parent.command.get_params(self): ++ parent_command_path.extend(param.get_usage_pieces(self)) ++ ++ rv = f"{' '.join(parent_command_path)} {rv}" ++ return rv.lstrip() ++ ++ def find_root(self) -> Context: ++ """Finds the outermost context.""" ++ node = self ++ while node.parent is not None: ++ node = node.parent ++ return node ++ ++ def find_object(self, object_type: type[V]) -> V | None: ++ """Finds the closest object of a given type.""" ++ node: Context | None = self ++ ++ while node is not None: ++ if isinstance(node.obj, object_type): ++ return node.obj ++ ++ node = node.parent ++ ++ return None ++ ++ def ensure_object(self, object_type: type[V]) -> V: ++ """Like :meth:`find_object` but sets the innermost object to a ++ new instance of `object_type` if it does not exist. ++ """ ++ rv = self.find_object(object_type) ++ if rv is None: ++ self.obj = rv = object_type() ++ return rv ++ ++ @t.overload ++ def lookup_default( ++ self, name: str, call: t.Literal[True] = True ++ ) -> t.Any | None: ... ++ ++ @t.overload ++ def lookup_default( ++ self, name: str, call: t.Literal[False] = ... ++ ) -> t.Any | t.Callable[[], t.Any] | None: ... ++ ++ def lookup_default(self, name: str, call: bool = True) -> t.Any | None: ++ """Get the default for a parameter from :attr:`default_map`. ++ ++ :param name: Name of the parameter. ++ :param call: If the default is a callable, call it. Disable to ++ return the callable instead. ++ ++ .. versionchanged:: 8.0 ++ Added the ``call`` parameter. ++ """ ++ if self.default_map is not None: ++ value = self.default_map.get(name) ++ ++ if call and callable(value): ++ return value() ++ ++ return value ++ ++ return None ++ ++ def fail(self, message: str) -> t.NoReturn: ++ """Aborts the execution of the program with a specific error ++ message. ++ ++ :param message: the error message to fail with. ++ """ ++ raise UsageError(message, self) ++ ++ def abort(self) -> t.NoReturn: ++ """Aborts the script.""" ++ raise Abort() ++ ++ def exit(self, code: int = 0) -> t.NoReturn: ++ """Exits the application with a given exit code. ++ ++ .. versionchanged:: 8.2 ++ Callbacks and context managers registered with :meth:`call_on_close` ++ and :meth:`with_resource` are closed before exiting. ++ """ ++ self.close() ++ raise Exit(code) ++ ++ def get_usage(self) -> str: ++ """Helper method to get formatted usage string for the current ++ context and command. ++ """ ++ return self.command.get_usage(self) ++ + def get_help(self) -> str: + """Helper method to get formatted help page for the current + context and command. + """ + return self.command.get_help(self) + +- def get_usage(self) -> str: +- """Helper method to get formatted usage string for the current +- context and command. +- """ +- return self.command.get_usage(self) ++ def _make_sub_context(self, command: Command) -> Context: ++ """Create a new context of the same type as this context, but ++ for a new command. ++ ++ :meta private: ++ """ ++ return type(self)(command, info_name=command.name, parent=self) ++ ++ @t.overload ++ def invoke( ++ self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any ++ ) -> V: ... ++ ++ @t.overload ++ def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... + + def invoke( + self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any +@@ -597,12 +786,33 @@ + with ctx: + return callback(*args, **kwargs) + +- def abort(self) -> t.NoReturn: +- """Aborts the script.""" +- raise Abort() +- +- @t.overload +- def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... ++ def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ++ """Similar to :meth:`invoke` but fills in default keyword ++ arguments from the current context if the other command expects ++ it. This cannot invoke callbacks directly, only other commands. ++ ++ .. versionchanged:: 8.0 ++ All ``kwargs`` are tracked in :attr:`params` so they will be ++ passed if ``forward`` is called at multiple levels. ++ """ ++ # Can only forward to other commands, not direct callbacks. ++ if not isinstance(cmd, Command): ++ raise TypeError("Callback is not a command.") ++ ++ for param in self.params: ++ if param not in kwargs: ++ kwargs[param] = self.params[param] ++ ++ return self.invoke(cmd, *args, **kwargs) ++ ++ def set_parameter_source(self, name: str, source: ParameterSource) -> None: ++ """Set the source of a parameter. This indicates the location ++ from which the value of the parameter was obtained. ++ ++ :param name: The name of the parameter. ++ :param source: A member of :class:`~click.core.ParameterSource`. ++ """ ++ self._parameter_source[name] = source + + def get_parameter_source(self, name: str) -> ParameterSource | None: + """Get the source of a parameter. This indicates the location +@@ -622,215 +832,6 @@ + """ + return self._parameter_source.get(name) + +- def set_parameter_source(self, name: str, source: ParameterSource) -> None: +- """Set the source of a parameter. This indicates the location +- from which the value of the parameter was obtained. +- +- :param name: The name of the parameter. +- :param source: A member of :class:`~click.core.ParameterSource`. +- """ +- self._parameter_source[name] = source +- +- @property +- def command_path(self) -> str: +- """The computed command path. This is used for the ``usage`` +- information on the help page. It's automatically created by +- combining the info names of the chain of contexts to the root. +- """ +- rv = "" +- if self.info_name is not None: +- rv = self.info_name +- if self.parent is not None: +- parent_command_path = [self.parent.command_path] +- +- if isinstance(self.parent.command, Command): +- for param in self.parent.command.get_params(self): +- parent_command_path.extend(param.get_usage_pieces(self)) +- +- rv = f"{' '.join(parent_command_path)} {rv}" +- return rv.lstrip() +- +- @t.overload +- def lookup_default( +- self, name: str, call: t.Literal[True] = True +- ) -> t.Any | None: ... +- +- def to_info_dict(self) -> dict[str, t.Any]: +- """Gather information that could be useful for a tool generating +- user-facing documentation. This traverses the entire CLI +- structure. +- +- .. code-block:: python +- +- with Context(cli) as ctx: +- info = ctx.to_info_dict() +- +- .. versionadded:: 8.0 +- """ +- return { +- "command": self.command.to_info_dict(self), +- "info_name": self.info_name, +- "allow_extra_args": self.allow_extra_args, +- "allow_interspersed_args": self.allow_interspersed_args, +- "ignore_unknown_options": self.ignore_unknown_options, +- "auto_envvar_prefix": self.auto_envvar_prefix, +- } +- +- def _make_sub_context(self, command: Command) -> Context: +- """Create a new context of the same type as this context, but +- for a new command. +- +- :meta private: +- """ +- return type(self)(command, info_name=command.name, parent=self) +- +- def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: +- """Register a function to be called when the context tears down. +- +- This can be used to close resources opened during the script +- execution. Resources that support Python's context manager +- protocol which would be used in a ``with`` statement should be +- registered with :meth:`with_resource` instead. +- +- :param f: The function to execute on teardown. +- """ +- return self._exit_stack.callback(f) +- +- @property +- def meta(self) -> dict[str, t.Any]: +- """This is a dictionary which is shared with all the contexts +- that are nested. It exists so that click utilities can store some +- state here if they need to. It is however the responsibility of +- that code to manage this dictionary well. +- +- The keys are supposed to be unique dotted strings. For instance +- module paths are a good choice for it. What is stored in there is +- irrelevant for the operation of click. However what is important is +- that code that places data here adheres to the general semantics of +- the system. +- +- Example usage:: +- +- LANG_KEY = f'{__name__}.lang' +- +- def set_language(value): +- ctx = get_current_context() +- ctx.meta[LANG_KEY] = value +- +- def get_language(): +- return get_current_context().meta.get(LANG_KEY, 'en_US') +- +- .. versionadded:: 5.0 +- """ +- return self._meta +- +- def find_root(self) -> Context: +- """Finds the outermost context.""" +- node = self +- while node.parent is not None: +- node = node.parent +- return node +- +- def make_formatter(self) -> HelpFormatter: +- """Creates the :class:`~click.HelpFormatter` for the help and +- usage output. +- +- To quickly customize the formatter class used without overriding +- this method, set the :attr:`formatter_class` attribute. +- +- .. versionchanged:: 8.0 +- Added the :attr:`formatter_class` attribute. +- """ +- return self.formatter_class( +- width=self.terminal_width, max_width=self.max_content_width +- ) +- +- def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: +- """Similar to :meth:`invoke` but fills in default keyword +- arguments from the current context if the other command expects +- it. This cannot invoke callbacks directly, only other commands. +- +- .. versionchanged:: 8.0 +- All ``kwargs`` are tracked in :attr:`params` so they will be +- passed if ``forward`` is called at multiple levels. +- """ +- # Can only forward to other commands, not direct callbacks. +- if not isinstance(cmd, Command): +- raise TypeError("Callback is not a command.") +- +- for param in self.params: +- if param not in kwargs: +- kwargs[param] = self.params[param] +- +- return self.invoke(cmd, *args, **kwargs) +- +- def lookup_default(self, name: str, call: bool = True) -> t.Any | None: +- """Get the default for a parameter from :attr:`default_map`. +- +- :param name: Name of the parameter. +- :param call: If the default is a callable, call it. Disable to +- return the callable instead. +- +- .. versionchanged:: 8.0 +- Added the ``call`` parameter. +- """ +- if self.default_map is not None: +- value = self.default_map.get(name) +- +- if call and callable(value): +- return value() +- +- return value +- +- return None +- +- def exit(self, code: int = 0) -> t.NoReturn: +- """Exits the application with a given exit code. +- +- .. versionchanged:: 8.2 +- Callbacks and context managers registered with :meth:`call_on_close` +- and :meth:`with_resource` are closed before exiting. +- """ +- self.close() +- raise Exit(code) +- +- def close(self) -> None: +- """Invoke all close callbacks registered with +- :meth:`call_on_close`, and exit all context managers entered +- with :meth:`with_resource`. +- """ +- self._exit_stack.close() +- # In case the context is reused, create a new exit stack. +- self._exit_stack = ExitStack() +- +- def with_resource(self, context_manager: AbstractContextManager[V]) -> V: +- """Register a resource as if it were used in a ``with`` +- statement. The resource will be cleaned up when the context is +- popped. +- +- Uses :meth:`contextlib.ExitStack.enter_context`. It calls the +- resource's ``__enter__()`` method and returns the result. When +- the context is popped, it closes the stack, which calls the +- resource's ``__exit__()`` method. +- +- To register a cleanup function for something that isn't a +- context manager, use :meth:`call_on_close`. Or use something +- from :mod:`contextlib` to turn it into a context manager first. +- +- .. code-block:: python +- +- @click.group() +- @click.option("--name") +- @click.pass_context +- def cli(ctx): +- ctx.obj = ctx.with_resource(connect_db(name)) +- +- :param context_manager: The context manager to enter. +- :return: Whatever ``context_manager.__enter__()`` returns. +- +- .. versionadded:: 8.0 +- """ +- return self._exit_stack.enter_context(context_manager) + + class Command: + """Commands are the basic building block of command line interfaces in +@@ -2695,7 +2696,7 @@ + any_prefix_is_slash = True + + if not self.is_flag and not self.count: +- pass ++ rv += f" {self.make_metavar()}" + + return rv + +@@ -2707,6 +2708,7 @@ + help = self.help or "" + + extra = self.get_help_extra(ctx) ++ extra_items = [] + if "envvars" in extra: + extra_items.append( + _("env var: {var}").format(var=", ".join(extra["envvars"])) +@@ -2719,9 +2721,11 @@ + extra_items.append(_(extra["required"])) + + if extra_items: ++ extra_str = "; ".join(extra_items) + help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" + + return ("; " if any_prefix_is_slash else " / ").join(rv), help ++ + def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: + extra: types.OptionHelpExtra = {} + diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__k328265n/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6c3bbbf96d6e28a4e42455b9a25d0471b56ea07f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/solution/solve.sh @@ -0,0 +1,661 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/core.py b/src/click/core.py +index 8943123d5dc860b236e175773722c8c38004b736..abe9fa9bb2bd9179031f5963749b36697309fbc1 100644 +--- a/src/click/core.py ++++ b/src/click/core.py +@@ -125,9 +125,9 @@ + try: + idx: float = invocation_order.index(item) + except ValueError: +- idx = float("-inf") +- +- return item.is_eager, idx ++ idx = float("inf") ++ ++ return not item.is_eager, idx + + return sorted(declaration_order, key=sort_key) + +@@ -262,59 +262,6 @@ + #: .. versionadded:: 8.0 + formatter_class: type[HelpFormatter] = HelpFormatter + +- @t.overload +- def invoke( +- self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any +- ) -> V: ... +- +- def __exit__( +- self, +- exc_type: type[BaseException] | None, +- exc_value: BaseException | None, +- tb: TracebackType | None, +- ) -> None: +- self._depth -= 1 +- if self._depth == 0: +- self.close() +- pop_context() +- +- @property +- def protected_args(self) -> list[str]: +- import warnings +- +- warnings.warn( +- "'protected_args' is deprecated and will be removed in Click 9.0." +- " 'args' will contain remaining unparsed tokens.", +- DeprecationWarning, +- stacklevel=2, +- ) +- return self._protected_args +- +- def find_object(self, object_type: type[V]) -> V | None: +- """Finds the closest object of a given type.""" +- node: Context | None = self +- +- while node is not None: +- if isinstance(node.obj, object_type): +- return node.obj +- +- node = node.parent +- +- return None +- +- def fail(self, message: str) -> t.NoReturn: +- """Aborts the execution of the program with a specific error +- message. +- +- :param message: the error message to fail with. +- """ +- raise UsageError(message, self) +- +- @t.overload +- def lookup_default( +- self, name: str, call: t.Literal[False] = ... +- ) -> t.Any | t.Callable[[], t.Any] | None: ... +- + def __init__( + self, + command: Command, +@@ -485,19 +432,54 @@ + self._parameter_source: dict[str, ParameterSource] = {} + self._exit_stack = ExitStack() + +- def ensure_object(self, object_type: type[V]) -> V: +- """Like :meth:`find_object` but sets the innermost object to a +- new instance of `object_type` if it does not exist. +- """ +- rv = self.find_object(object_type) +- if rv is None: +- self.obj = rv = object_type() +- return rv ++ @property ++ def protected_args(self) -> list[str]: ++ import warnings ++ ++ warnings.warn( ++ "'protected_args' is deprecated and will be removed in Click 9.0." ++ " 'args' will contain remaining unparsed tokens.", ++ DeprecationWarning, ++ stacklevel=2, ++ ) ++ return self._protected_args ++ ++ def to_info_dict(self) -> dict[str, t.Any]: ++ """Gather information that could be useful for a tool generating ++ user-facing documentation. This traverses the entire CLI ++ structure. ++ ++ .. code-block:: python ++ ++ with Context(cli) as ctx: ++ info = ctx.to_info_dict() ++ ++ .. versionadded:: 8.0 ++ """ ++ return { ++ "command": self.command.to_info_dict(self), ++ "info_name": self.info_name, ++ "allow_extra_args": self.allow_extra_args, ++ "allow_interspersed_args": self.allow_interspersed_args, ++ "ignore_unknown_options": self.ignore_unknown_options, ++ "auto_envvar_prefix": self.auto_envvar_prefix, ++ } + + def __enter__(self) -> Context: + self._depth += 1 + push_context(self) + return self ++ ++ def __exit__( ++ self, ++ exc_type: type[BaseException] | None, ++ exc_value: BaseException | None, ++ tb: TracebackType | None, ++ ) -> None: ++ self._depth -= 1 ++ if self._depth == 0: ++ self.close() ++ pop_context() + + @contextmanager + def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]: +@@ -537,17 +519,224 @@ + if not cleanup: + self._depth -= 1 + ++ @property ++ def meta(self) -> dict[str, t.Any]: ++ """This is a dictionary which is shared with all the contexts ++ that are nested. It exists so that click utilities can store some ++ state here if they need to. It is however the responsibility of ++ that code to manage this dictionary well. ++ ++ The keys are supposed to be unique dotted strings. For instance ++ module paths are a good choice for it. What is stored in there is ++ irrelevant for the operation of click. However what is important is ++ that code that places data here adheres to the general semantics of ++ the system. ++ ++ Example usage:: ++ ++ LANG_KEY = f'{__name__}.lang' ++ ++ def set_language(value): ++ ctx = get_current_context() ++ ctx.meta[LANG_KEY] = value ++ ++ def get_language(): ++ return get_current_context().meta.get(LANG_KEY, 'en_US') ++ ++ .. versionadded:: 5.0 ++ """ ++ return self._meta ++ ++ def make_formatter(self) -> HelpFormatter: ++ """Creates the :class:`~click.HelpFormatter` for the help and ++ usage output. ++ ++ To quickly customize the formatter class used without overriding ++ this method, set the :attr:`formatter_class` attribute. ++ ++ .. versionchanged:: 8.0 ++ Added the :attr:`formatter_class` attribute. ++ """ ++ return self.formatter_class( ++ width=self.terminal_width, max_width=self.max_content_width ++ ) ++ ++ def with_resource(self, context_manager: AbstractContextManager[V]) -> V: ++ """Register a resource as if it were used in a ``with`` ++ statement. The resource will be cleaned up when the context is ++ popped. ++ ++ Uses :meth:`contextlib.ExitStack.enter_context`. It calls the ++ resource's ``__enter__()`` method and returns the result. When ++ the context is popped, it closes the stack, which calls the ++ resource's ``__exit__()`` method. ++ ++ To register a cleanup function for something that isn't a ++ context manager, use :meth:`call_on_close`. Or use something ++ from :mod:`contextlib` to turn it into a context manager first. ++ ++ .. code-block:: python ++ ++ @click.group() ++ @click.option("--name") ++ @click.pass_context ++ def cli(ctx): ++ ctx.obj = ctx.with_resource(connect_db(name)) ++ ++ :param context_manager: The context manager to enter. ++ :return: Whatever ``context_manager.__enter__()`` returns. ++ ++ .. versionadded:: 8.0 ++ """ ++ return self._exit_stack.enter_context(context_manager) ++ ++ def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: ++ """Register a function to be called when the context tears down. ++ ++ This can be used to close resources opened during the script ++ execution. Resources that support Python's context manager ++ protocol which would be used in a ``with`` statement should be ++ registered with :meth:`with_resource` instead. ++ ++ :param f: The function to execute on teardown. ++ """ ++ return self._exit_stack.callback(f) ++ ++ def close(self) -> None: ++ """Invoke all close callbacks registered with ++ :meth:`call_on_close`, and exit all context managers entered ++ with :meth:`with_resource`. ++ """ ++ self._exit_stack.close() ++ # In case the context is reused, create a new exit stack. ++ self._exit_stack = ExitStack() ++ ++ @property ++ def command_path(self) -> str: ++ """The computed command path. This is used for the ``usage`` ++ information on the help page. It's automatically created by ++ combining the info names of the chain of contexts to the root. ++ """ ++ rv = "" ++ if self.info_name is not None: ++ rv = self.info_name ++ if self.parent is not None: ++ parent_command_path = [self.parent.command_path] ++ ++ if isinstance(self.parent.command, Command): ++ for param in self.parent.command.get_params(self): ++ parent_command_path.extend(param.get_usage_pieces(self)) ++ ++ rv = f"{' '.join(parent_command_path)} {rv}" ++ return rv.lstrip() ++ ++ def find_root(self) -> Context: ++ """Finds the outermost context.""" ++ node = self ++ while node.parent is not None: ++ node = node.parent ++ return node ++ ++ def find_object(self, object_type: type[V]) -> V | None: ++ """Finds the closest object of a given type.""" ++ node: Context | None = self ++ ++ while node is not None: ++ if isinstance(node.obj, object_type): ++ return node.obj ++ ++ node = node.parent ++ ++ return None ++ ++ def ensure_object(self, object_type: type[V]) -> V: ++ """Like :meth:`find_object` but sets the innermost object to a ++ new instance of `object_type` if it does not exist. ++ """ ++ rv = self.find_object(object_type) ++ if rv is None: ++ self.obj = rv = object_type() ++ return rv ++ ++ @t.overload ++ def lookup_default( ++ self, name: str, call: t.Literal[True] = True ++ ) -> t.Any | None: ... ++ ++ @t.overload ++ def lookup_default( ++ self, name: str, call: t.Literal[False] = ... ++ ) -> t.Any | t.Callable[[], t.Any] | None: ... ++ ++ def lookup_default(self, name: str, call: bool = True) -> t.Any | None: ++ """Get the default for a parameter from :attr:`default_map`. ++ ++ :param name: Name of the parameter. ++ :param call: If the default is a callable, call it. Disable to ++ return the callable instead. ++ ++ .. versionchanged:: 8.0 ++ Added the ``call`` parameter. ++ """ ++ if self.default_map is not None: ++ value = self.default_map.get(name) ++ ++ if call and callable(value): ++ return value() ++ ++ return value ++ ++ return None ++ ++ def fail(self, message: str) -> t.NoReturn: ++ """Aborts the execution of the program with a specific error ++ message. ++ ++ :param message: the error message to fail with. ++ """ ++ raise UsageError(message, self) ++ ++ def abort(self) -> t.NoReturn: ++ """Aborts the script.""" ++ raise Abort() ++ ++ def exit(self, code: int = 0) -> t.NoReturn: ++ """Exits the application with a given exit code. ++ ++ .. versionchanged:: 8.2 ++ Callbacks and context managers registered with :meth:`call_on_close` ++ and :meth:`with_resource` are closed before exiting. ++ """ ++ self.close() ++ raise Exit(code) ++ ++ def get_usage(self) -> str: ++ """Helper method to get formatted usage string for the current ++ context and command. ++ """ ++ return self.command.get_usage(self) ++ + def get_help(self) -> str: + """Helper method to get formatted help page for the current + context and command. + """ + return self.command.get_help(self) + +- def get_usage(self) -> str: +- """Helper method to get formatted usage string for the current +- context and command. +- """ +- return self.command.get_usage(self) ++ def _make_sub_context(self, command: Command) -> Context: ++ """Create a new context of the same type as this context, but ++ for a new command. ++ ++ :meta private: ++ """ ++ return type(self)(command, info_name=command.name, parent=self) ++ ++ @t.overload ++ def invoke( ++ self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any ++ ) -> V: ... ++ ++ @t.overload ++ def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... + + def invoke( + self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any +@@ -597,12 +786,33 @@ + with ctx: + return callback(*args, **kwargs) + +- def abort(self) -> t.NoReturn: +- """Aborts the script.""" +- raise Abort() +- +- @t.overload +- def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... ++ def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ++ """Similar to :meth:`invoke` but fills in default keyword ++ arguments from the current context if the other command expects ++ it. This cannot invoke callbacks directly, only other commands. ++ ++ .. versionchanged:: 8.0 ++ All ``kwargs`` are tracked in :attr:`params` so they will be ++ passed if ``forward`` is called at multiple levels. ++ """ ++ # Can only forward to other commands, not direct callbacks. ++ if not isinstance(cmd, Command): ++ raise TypeError("Callback is not a command.") ++ ++ for param in self.params: ++ if param not in kwargs: ++ kwargs[param] = self.params[param] ++ ++ return self.invoke(cmd, *args, **kwargs) ++ ++ def set_parameter_source(self, name: str, source: ParameterSource) -> None: ++ """Set the source of a parameter. This indicates the location ++ from which the value of the parameter was obtained. ++ ++ :param name: The name of the parameter. ++ :param source: A member of :class:`~click.core.ParameterSource`. ++ """ ++ self._parameter_source[name] = source + + def get_parameter_source(self, name: str) -> ParameterSource | None: + """Get the source of a parameter. This indicates the location +@@ -622,215 +832,6 @@ + """ + return self._parameter_source.get(name) + +- def set_parameter_source(self, name: str, source: ParameterSource) -> None: +- """Set the source of a parameter. This indicates the location +- from which the value of the parameter was obtained. +- +- :param name: The name of the parameter. +- :param source: A member of :class:`~click.core.ParameterSource`. +- """ +- self._parameter_source[name] = source +- +- @property +- def command_path(self) -> str: +- """The computed command path. This is used for the ``usage`` +- information on the help page. It's automatically created by +- combining the info names of the chain of contexts to the root. +- """ +- rv = "" +- if self.info_name is not None: +- rv = self.info_name +- if self.parent is not None: +- parent_command_path = [self.parent.command_path] +- +- if isinstance(self.parent.command, Command): +- for param in self.parent.command.get_params(self): +- parent_command_path.extend(param.get_usage_pieces(self)) +- +- rv = f"{' '.join(parent_command_path)} {rv}" +- return rv.lstrip() +- +- @t.overload +- def lookup_default( +- self, name: str, call: t.Literal[True] = True +- ) -> t.Any | None: ... +- +- def to_info_dict(self) -> dict[str, t.Any]: +- """Gather information that could be useful for a tool generating +- user-facing documentation. This traverses the entire CLI +- structure. +- +- .. code-block:: python +- +- with Context(cli) as ctx: +- info = ctx.to_info_dict() +- +- .. versionadded:: 8.0 +- """ +- return { +- "command": self.command.to_info_dict(self), +- "info_name": self.info_name, +- "allow_extra_args": self.allow_extra_args, +- "allow_interspersed_args": self.allow_interspersed_args, +- "ignore_unknown_options": self.ignore_unknown_options, +- "auto_envvar_prefix": self.auto_envvar_prefix, +- } +- +- def _make_sub_context(self, command: Command) -> Context: +- """Create a new context of the same type as this context, but +- for a new command. +- +- :meta private: +- """ +- return type(self)(command, info_name=command.name, parent=self) +- +- def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: +- """Register a function to be called when the context tears down. +- +- This can be used to close resources opened during the script +- execution. Resources that support Python's context manager +- protocol which would be used in a ``with`` statement should be +- registered with :meth:`with_resource` instead. +- +- :param f: The function to execute on teardown. +- """ +- return self._exit_stack.callback(f) +- +- @property +- def meta(self) -> dict[str, t.Any]: +- """This is a dictionary which is shared with all the contexts +- that are nested. It exists so that click utilities can store some +- state here if they need to. It is however the responsibility of +- that code to manage this dictionary well. +- +- The keys are supposed to be unique dotted strings. For instance +- module paths are a good choice for it. What is stored in there is +- irrelevant for the operation of click. However what is important is +- that code that places data here adheres to the general semantics of +- the system. +- +- Example usage:: +- +- LANG_KEY = f'{__name__}.lang' +- +- def set_language(value): +- ctx = get_current_context() +- ctx.meta[LANG_KEY] = value +- +- def get_language(): +- return get_current_context().meta.get(LANG_KEY, 'en_US') +- +- .. versionadded:: 5.0 +- """ +- return self._meta +- +- def find_root(self) -> Context: +- """Finds the outermost context.""" +- node = self +- while node.parent is not None: +- node = node.parent +- return node +- +- def make_formatter(self) -> HelpFormatter: +- """Creates the :class:`~click.HelpFormatter` for the help and +- usage output. +- +- To quickly customize the formatter class used without overriding +- this method, set the :attr:`formatter_class` attribute. +- +- .. versionchanged:: 8.0 +- Added the :attr:`formatter_class` attribute. +- """ +- return self.formatter_class( +- width=self.terminal_width, max_width=self.max_content_width +- ) +- +- def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: +- """Similar to :meth:`invoke` but fills in default keyword +- arguments from the current context if the other command expects +- it. This cannot invoke callbacks directly, only other commands. +- +- .. versionchanged:: 8.0 +- All ``kwargs`` are tracked in :attr:`params` so they will be +- passed if ``forward`` is called at multiple levels. +- """ +- # Can only forward to other commands, not direct callbacks. +- if not isinstance(cmd, Command): +- raise TypeError("Callback is not a command.") +- +- for param in self.params: +- if param not in kwargs: +- kwargs[param] = self.params[param] +- +- return self.invoke(cmd, *args, **kwargs) +- +- def lookup_default(self, name: str, call: bool = True) -> t.Any | None: +- """Get the default for a parameter from :attr:`default_map`. +- +- :param name: Name of the parameter. +- :param call: If the default is a callable, call it. Disable to +- return the callable instead. +- +- .. versionchanged:: 8.0 +- Added the ``call`` parameter. +- """ +- if self.default_map is not None: +- value = self.default_map.get(name) +- +- if call and callable(value): +- return value() +- +- return value +- +- return None +- +- def exit(self, code: int = 0) -> t.NoReturn: +- """Exits the application with a given exit code. +- +- .. versionchanged:: 8.2 +- Callbacks and context managers registered with :meth:`call_on_close` +- and :meth:`with_resource` are closed before exiting. +- """ +- self.close() +- raise Exit(code) +- +- def close(self) -> None: +- """Invoke all close callbacks registered with +- :meth:`call_on_close`, and exit all context managers entered +- with :meth:`with_resource`. +- """ +- self._exit_stack.close() +- # In case the context is reused, create a new exit stack. +- self._exit_stack = ExitStack() +- +- def with_resource(self, context_manager: AbstractContextManager[V]) -> V: +- """Register a resource as if it were used in a ``with`` +- statement. The resource will be cleaned up when the context is +- popped. +- +- Uses :meth:`contextlib.ExitStack.enter_context`. It calls the +- resource's ``__enter__()`` method and returns the result. When +- the context is popped, it closes the stack, which calls the +- resource's ``__exit__()`` method. +- +- To register a cleanup function for something that isn't a +- context manager, use :meth:`call_on_close`. Or use something +- from :mod:`contextlib` to turn it into a context manager first. +- +- .. code-block:: python +- +- @click.group() +- @click.option("--name") +- @click.pass_context +- def cli(ctx): +- ctx.obj = ctx.with_resource(connect_db(name)) +- +- :param context_manager: The context manager to enter. +- :return: Whatever ``context_manager.__enter__()`` returns. +- +- .. versionadded:: 8.0 +- """ +- return self._exit_stack.enter_context(context_manager) + + class Command: + """Commands are the basic building block of command line interfaces in +@@ -2695,7 +2696,7 @@ + any_prefix_is_slash = True + + if not self.is_flag and not self.count: +- pass ++ rv += f" {self.make_metavar()}" + + return rv + +@@ -2707,6 +2708,7 @@ + help = self.help or "" + + extra = self.get_help_extra(ctx) ++ extra_items = [] + if "envvars" in extra: + extra_items.append( + _("env var: {var}").format(var=", ".join(extra["envvars"])) +@@ -2719,9 +2721,11 @@ + extra_items.append(_(extra["required"])) + + if extra_items: ++ extra_str = "; ".join(extra_items) + help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" + + return ("; " if any_prefix_is_slash else " / ").join(rv), help ++ + def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: + extra: types.OptionHelpExtra = {} + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/task.toml b/tasks/pallets__click.fde47b4b.combine_file__k328265n/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..5f9fb51a1ba35d4594573823629b0d3ef72d84ee --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "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[-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_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_basic.py::test_basic_functionality", + "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_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_basic.py::test_help_invalid_default", + "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_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_command_no_args_is_help", + "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_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_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_propagate_show_default_setting", + "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_context_formatter_class", + "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_nested", + "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_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_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_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=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_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_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_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_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_multiple_option_with_optional_value", + "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_is_iterator", + "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_update_with_item_show_func", + "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_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_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_utils.py::test_echo", + "tests/test_utils.py::test_prompts", + "tests/test_utils.py::test_open_file", + "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_nargs_envvar[2--None]", + "tests/test_arguments.py::test_missing_arg", + "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_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_repr", + "tests/test_basic.py::test_required_option", + "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_group_add_command_name", + "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_compat.py::test_is_jupyter_kernel_output", + "tests/test_context.py::test_make_pass_meta_decorator_doc", + "tests/test_context.py::test_context_pushing", + "tests/test_context.py::test_with_resource", + "tests/test_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "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_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_no_help", + "tests/test_formatting.py::test_formatting_usage_custom_help", + "tests/test_formatting.py::test_removing_multiline_marker", + "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_unknown_options[--foo]", + "tests/test_options.py::test_unknown_options[-f]", + "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_missing_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "tests/test_options.py::test_flag_duplicate_names", + "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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_shell_completion.py::test_files_closed", + "tests/test_termui.py::test_progressbar_hidden_manual", + "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_choices_list_in_prompt", + "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_progressbar_item_show_func", + "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_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_false_show_default_cause_no_default_display_in_prompt", + "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-00.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_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_pathlib_dash", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..07bbda54a142a27a76e93e6f977a405708e90a58 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/canaries/first-hunk-only.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/core.py b/src/click/core.py +index 8943123d5dc860b236e175773722c8c38004b736..abe9fa9bb2bd9179031f5963749b36697309fbc1 100644 +--- a/src/click/core.py ++++ b/src/click/core.py +@@ -125,9 +125,9 @@ + try: + idx: float = invocation_order.index(item) + except ValueError: +- idx = float("-inf") +- +- return item.is_eager, idx ++ idx = float("inf") ++ ++ return not item.is_eager, idx + + return sorted(declaration_order, key=sort_key) + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__k328265n/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..325375f56570a731fd49dfd8a23ff0b632337249 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "0b48fb69d701716eef8318ede460a6513d6102d54a0da01ae070c6eb3e7b3dc9", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "864049ca85244306061ec42ea47ac57427ef2707994efaf1595dc4e1a6eba1eb", + "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": "273c65162f308e8440684d8ab7df656cd3e8c8de2c956e382b556a46780582a9", + "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": "29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28", + "source_completion_sha256": "2ff20ab79dd0780ae767c31f1a60e3dad08e633d3e7768a0d03b17a2775fe48a", + "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__kjhfdfla", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "73cac9f50ea6d225d12fa7b34aa60162f57b79fcf5429da57323ff95acf2b905", + "is_fork": true, + "learner_path": "tasks/e8864bc26efe5b256cfc057a/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/29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28/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": "983821717c493fc053358d2aca3ec7f9997559cdf4b4a681c8f08baebfcdcaa8", + "provenance_path": "tasks/e8864bc26efe5b256cfc057a/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e89af04e09d34f46e0a31f2c8f2c27a3e7a0dbaf", + "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__kjhfdfla", + "task_sha256": "2b994e5e7227dca233474c333fe14aca66908932b2d266b4e6ad7c1e6069c210", + "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__kjhfdfla", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3ff7205e708dcf025af58cbecd1c98a41b7f3d4 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/instruction.md @@ -0,0 +1,46 @@ +LazyFile not closing files properly when should_close is True + +#### Description + +LazyFile instances are not closing files when they should be closed, causing resource leaks and test failures. The `close_intelligently()` method appears to have inverted logic - it's only closing files when `should_close` is False instead of when it's True. + +#### Steps/Code to Reproduce + +```python +import click +import tempfile +import os + +# Create a temporary file +with tempfile.NamedTemporaryFile(mode='w', delete=False) as f: + f.write('test content\n') + temp_file = f.name + +try: + # Use LazyFile to open the file + with click.utils.LazyFile(temp_file, 'r') as lf: + content = lf.read() + print(f"Read: {content.strip()}") + + # Try to delete the file - this should work if the file was properly closed + os.unlink(temp_file) + print("File deleted successfully") + +except Exception as e: + print(f"Error: {e}") + # Clean up if deletion failed + try: + os.unlink(temp_file) + except: + pass +``` + +On systems where file handles aren't automatically released, this may fail to delete the file because LazyFile didn't close it properly. + +#### Expected Behavior + +LazyFile should close files that it opened (when `should_close` is True) and leave files open that were passed to it already opened (when `should_close` is False). + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..f9084e2e7f72c2bfc373adb3e612dbe3ca235d61 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/metadata.json @@ -0,0 +1,743 @@ +{ + "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_file_args", + "tests/test_arguments.py::test_file_atomics", + "tests/test_basic.py::test_file_option", + "tests/test_basic.py::test_file_lazy_mode", + "tests/test_shell_completion.py::test_files_closed", + "tests/test_utils.py::test_iter_lazyfile" + ], + "PASS_TO_PASS": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_path_allow_dash", + "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_missing_argument_string_cast", + "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_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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_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_progressbar_update", + "tests/test_termui.py::test_progressbar_item_show_func", + "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_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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "tests/test_utils.py::test_iter_keepopenfile", + "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": "e89af04e09d34f46e0a31f2c8f2c27a3e7a0dbaf", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28" + }, + "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_chain.py", + "/testbed/tests/test_command_decorators.py", + "/testbed/tests/test_commands.py", + "/testbed/tests/test_compat.py", + "/testbed/tests/test_context.py", + "/testbed/tests/test_custom_classes.py", + "/testbed/tests/test_defaults.py", + "/testbed/tests/test_formatting.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_normalization.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_termui.py", + "/testbed/tests/test_testing.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_shell_completion.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/utils.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2781722, + "task_id": "pallets__click.fde47b4b.combine_file__kjhfdfla", + "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__kjhfdfla", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "73cac9f50ea6d225d12fa7b34aa60162f57b79fcf5429da57323ff95acf2b905", + "is_fork": true, + "learner_path": "tasks/e8864bc26efe5b256cfc057a/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/29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28/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": "983821717c493fc053358d2aca3ec7f9997559cdf4b4a681c8f08baebfcdcaa8", + "provenance_path": "tasks/e8864bc26efe5b256cfc057a/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e89af04e09d34f46e0a31f2c8f2c27a3e7a0dbaf", + "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__kjhfdfla", + "task_sha256": "2b994e5e7227dca233474c333fe14aca66908932b2d266b4e6ad7c1e6069c210", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f8780c2051d8e7dcc8577eb35b65bef646be5121 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "0b48fb69d701716eef8318ede460a6513d6102d54a0da01ae070c6eb3e7b3dc9", + "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/29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "2ff20ab79dd0780ae767c31f1a60e3dad08e633d3e7768a0d03b17a2775fe48a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "8c1f26de252835735c064f394458bf2246b4de05049e0273b7f75cb2907441fa", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__kjhfdfla", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "73cac9f50ea6d225d12fa7b34aa60162f57b79fcf5429da57323ff95acf2b905", + "is_fork": true, + "learner_path": "tasks/e8864bc26efe5b256cfc057a/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/29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28/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": "983821717c493fc053358d2aca3ec7f9997559cdf4b4a681c8f08baebfcdcaa8", + "provenance_path": "tasks/e8864bc26efe5b256cfc057a/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "29ea6b7c9bfb3828cef8cd4e59ec53de6a0d9f28", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e89af04e09d34f46e0a31f2c8f2c27a3e7a0dbaf", + "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__kjhfdfla", + "task_sha256": "2b994e5e7227dca233474c333fe14aca66908932b2d266b4e6ad7c1e6069c210", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..46712a545bbd841731036ad3adcf50e673347230 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/provided-gold.diff @@ -0,0 +1,29 @@ +diff --git a/src/click/utils.py b/src/click/utils.py +index 08ad38d943b078d16aa9b06e9db324e27dfa3542..ab2fe5889cee75d559092442696f9b23bf20ebfb 100644 +--- a/src/click/utils.py ++++ b/src/click/utils.py +@@ -38,9 +38,10 @@ + + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: + try: +- return func(args, kwargs) ++ return func(*args, **kwargs) + except Exception: +- return None ++ pass ++ return None + + return update_wrapper(wrapper, func) + +@@ -172,9 +173,9 @@ + + def close_intelligently(self) -> None: + """This function only closes the file if it was opened by the lazy +- file wrapper. For instance this will never close stdin. ++ file wrapper. For instance this will never close stdin. + """ +- if not self.should_close: ++ if self.should_close: + self.close() + + def __enter__(self) -> LazyFile: diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7fc8c97362416d000790210dd78b83631fbdce5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/solution/solve.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/utils.py b/src/click/utils.py +index 08ad38d943b078d16aa9b06e9db324e27dfa3542..ab2fe5889cee75d559092442696f9b23bf20ebfb 100644 +--- a/src/click/utils.py ++++ b/src/click/utils.py +@@ -38,9 +38,10 @@ + + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: + try: +- return func(args, kwargs) ++ return func(*args, **kwargs) + except Exception: +- return None ++ pass ++ return None + + return update_wrapper(wrapper, func) + +@@ -172,9 +173,9 @@ + + def close_intelligently(self) -> None: + """This function only closes the file if it was opened by the lazy +- file wrapper. For instance this will never close stdin. ++ file wrapper. For instance this will never close stdin. + """ +- if not self.should_close: ++ if self.should_close: + self.close() + + def __enter__(self) -> LazyFile: +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/task.toml b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..408a5a0dcb258a19003e6735c0f147af15290b03 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/expected-panels.json @@ -0,0 +1,484 @@ +{ + "fail-to-pass": [ + "tests/test_arguments.py::test_file_args", + "tests/test_arguments.py::test_file_atomics", + "tests/test_basic.py::test_file_option", + "tests/test_basic.py::test_file_lazy_mode", + "tests/test_shell_completion.py::test_files_closed", + "tests/test_utils.py::test_iter_lazyfile" + ], + "pass-to-pass": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_path_allow_dash", + "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_missing_argument_string_cast", + "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_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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_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_progressbar_update", + "tests/test_termui.py::test_progressbar_item_show_func", + "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_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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "tests/test_utils.py::test_iter_keepopenfile", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..50bb6f875c7c48d28a55e27a65e2cfe3260df9b6 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/canaries/first-hunk-only.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/utils.py b/src/click/utils.py +index 08ad38d943b078d16aa9b06e9db324e27dfa3542..ab2fe5889cee75d559092442696f9b23bf20ebfb 100644 +--- a/src/click/utils.py ++++ b/src/click/utils.py +@@ -38,9 +38,10 @@ + + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: + try: +- return func(args, kwargs) ++ return func(*args, **kwargs) + except Exception: +- return None ++ pass ++ return None + + return update_wrapper(wrapper, func) + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__kjhfdfla/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..2983138a1c88b0f23843021e54b73fb93fe28112 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "bf20c33e762a952b6c492df8b3c11dbca94dbe69a7538e5e8e34c6ad6cc008b1", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "a9c67ff4351b4997662b6bf3acd0db4cc2cb98933014a3a1132bb70f3811da79", + "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": "3467f9a87e2f6bae0661420e9eb97086fdb7ce3bafed367125ef7aa3af6b742b", + "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": "9e39d28ffa6d0670f4d1ac851772cd623d3fc69a", + "source_completion_sha256": "075a3448eaa2460dd961efbea2e1a1ad2f00c49135574794519f03dd78eacdf5", + "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__l9cwqo65", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "b450f03e5059ecbfcf32044ab166a836c1b983f0d32c0a975f0699b29a100cc4", + "is_fork": true, + "learner_path": "tasks/529d24b347494ecc981f757f/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/9e39d28ffa6d0670f4d1ac851772cd623d3fc69a/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": "f947e077b6ceaca151b1ec34d1caaf6a9e77fee15366fbd049878766129c7b3f", + "provenance_path": "tasks/529d24b347494ecc981f757f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9e39d28ffa6d0670f4d1ac851772cd623d3fc69a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5486d3d96fccf00b02c51ddd27bb390ef89b04df", + "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__l9cwqo65", + "task_sha256": "d301126a2f6ea9b881b7e5495e7e90576b2d1c021daf5fe05a9d820470cd2c6f", + "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__l9cwqo65", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7febc07de452c8f5d792feae52c8a0394640057d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/instruction.md @@ -0,0 +1,49 @@ +# Progress bar rendering issues in Click + +I've noticed several issues with the progress bar rendering in Click. The progress bar doesn't display correctly in various scenarios. + +## Description + +The progress bar in Click has several rendering issues: + +1. The progress bar fills incorrectly - when it should be filled, it shows empty characters and vice versa +2. The information displayed in the progress bar is incorrect - position and percentage are swapped +3. The ETA is shown when it shouldn't be and hidden when it should be shown +4. The item_show_func doesn't receive the current item + +## Reproduction + +Here's a simple script to demonstrate the issues: + +```python +import click +import time + +@click.command() +def cli(): + # Test basic progress bar + with click.progressbar(range(10)) as progress: + for i in progress: + time.sleep(0.1) + + # Test with item_show_func + with click.progressbar(range(3), item_show_func=lambda x: f"Processing {x}") as progress: + for i in progress: + time.sleep(0.5) + print(f"\nCurrent item: {i}") + +if __name__ == "__main__": + cli() +``` + +When running this script, you'll notice: +- The progress bar fills incorrectly (empty characters where filled should be) +- The position and percentage information are in the wrong order +- The ETA information appears when it shouldn't +- The item_show_func doesn't show the correct current item + +This affects all progress bar functionality in Click. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..18021f67706dbac4096b6a6bef9d693184833d9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/metadata.json @@ -0,0 +1,744 @@ +{ + "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_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_item_show_func", + "tests/test_termui.py::test_progressbar_update_with_item_show_func" + ], + "PASS_TO_PASS": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_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_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_progressbar_update", + "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_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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "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": "5486d3d96fccf00b02c51ddd27bb390ef89b04df", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "9e39d28ffa6d0670f4d1ac851772cd623d3fc69a" + }, + "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_arguments.py", + "/testbed/tests/test_basic.py", + "/testbed/tests/test_chain.py", + "/testbed/tests/test_command_decorators.py", + "/testbed/tests/test_commands.py", + "/testbed/tests/test_compat.py", + "/testbed/tests/test_context.py", + "/testbed/tests/test_custom_classes.py", + "/testbed/tests/test_defaults.py", + "/testbed/tests/test_formatting.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_normalization.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_shell_completion.py", + "/testbed/tests/test_testing.py", + "/testbed/tests/test_types.py", + "/testbed/tests/test_utils.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_termui.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/_termui_impl.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2829969, + "task_id": "pallets__click.fde47b4b.combine_file__l9cwqo65", + "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__l9cwqo65", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "b450f03e5059ecbfcf32044ab166a836c1b983f0d32c0a975f0699b29a100cc4", + "is_fork": true, + "learner_path": "tasks/529d24b347494ecc981f757f/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/9e39d28ffa6d0670f4d1ac851772cd623d3fc69a/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": "f947e077b6ceaca151b1ec34d1caaf6a9e77fee15366fbd049878766129c7b3f", + "provenance_path": "tasks/529d24b347494ecc981f757f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9e39d28ffa6d0670f4d1ac851772cd623d3fc69a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5486d3d96fccf00b02c51ddd27bb390ef89b04df", + "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__l9cwqo65", + "task_sha256": "d301126a2f6ea9b881b7e5495e7e90576b2d1c021daf5fe05a9d820470cd2c6f", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..4fe013e5ef2073436cce0fec3b78ee911d3b35c0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "bf20c33e762a952b6c492df8b3c11dbca94dbe69a7538e5e8e34c6ad6cc008b1", + "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/9e39d28ffa6d0670f4d1ac851772cd623d3fc69a/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "075a3448eaa2460dd961efbea2e1a1ad2f00c49135574794519f03dd78eacdf5", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "86c5396be757045246539ee41e5e9609c91609c1fa4d2eb0e66fcb20679df3cb", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__l9cwqo65", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "b450f03e5059ecbfcf32044ab166a836c1b983f0d32c0a975f0699b29a100cc4", + "is_fork": true, + "learner_path": "tasks/529d24b347494ecc981f757f/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/9e39d28ffa6d0670f4d1ac851772cd623d3fc69a/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": "f947e077b6ceaca151b1ec34d1caaf6a9e77fee15366fbd049878766129c7b3f", + "provenance_path": "tasks/529d24b347494ecc981f757f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9e39d28ffa6d0670f4d1ac851772cd623d3fc69a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5486d3d96fccf00b02c51ddd27bb390ef89b04df", + "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__l9cwqo65", + "task_sha256": "d301126a2f6ea9b881b7e5495e7e90576b2d1c021daf5fe05a9d820470cd2c6f", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..cb4bf4c2c7b28ee318825c70b4369c740d29ee8c --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/provided-gold.diff @@ -0,0 +1,53 @@ +diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py +index f13582170c88d008e5a9c367f0dc753b74cb650f..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 + +@@ -208,17 +208,17 @@ + show_percent = self.show_percent + + info_bits = [] +- if self.length is not None and show_percent is not None: ++ if self.length is not None and show_percent is None: + show_percent = not self.show_pos + +- if not self.show_pos: ++ if self.show_pos: ++ info_bits.append(self.format_pos()) ++ if show_percent: + info_bits.append(self.format_pct()) +- if show_percent: +- info_bits.append(self.format_pos()) +- if self.show_eta or not self.eta_known or self.finished: ++ if self.show_eta and self.eta_known and not self.finished: + info_bits.append(self.format_eta()) + if self.item_show_func is not None: +- item_info = self.item_show_func(None) ++ item_info = self.item_show_func(self.current_item) + if item_info is not None: + info_bits.append(item_info) + diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..141d3f70532d562eca6ae23b614a37a39b00fbea --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/solution/solve.sh @@ -0,0 +1,59 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py +index f13582170c88d008e5a9c367f0dc753b74cb650f..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 + +@@ -208,17 +208,17 @@ + show_percent = self.show_percent + + info_bits = [] +- if self.length is not None and show_percent is not None: ++ if self.length is not None and show_percent is None: + show_percent = not self.show_pos + +- if not self.show_pos: ++ if self.show_pos: ++ info_bits.append(self.format_pos()) ++ if show_percent: + info_bits.append(self.format_pct()) +- if show_percent: +- info_bits.append(self.format_pos()) +- if self.show_eta or not self.eta_known or self.finished: ++ if self.show_eta and self.eta_known and not self.finished: + info_bits.append(self.format_eta()) + if self.item_show_func is not None: +- item_info = self.item_show_func(None) ++ item_info = self.item_show_func(self.current_item) + if item_info is not None: + info_bits.append(item_info) + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/task.toml b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..c4a31356a2417824a7321c2dcb9341fe9ba585d3 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "fail-to-pass": [ + "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_item_show_func", + "tests/test_termui.py::test_progressbar_update_with_item_show_func" + ], + "pass-to-pass": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_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_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_progressbar_update", + "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_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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..af109423c3eb10b06b1c601172f95be1e78f10f0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/canaries/first-hunk-only.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py +index f13582170c88d008e5a9c367f0dc753b74cb650f..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.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__l9cwqo65/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/adapter.json b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..2a4ebdc5ab35e341c943a27f9204ba3cd9747542 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "8f488b4afe7191d5fd5b058785050e3c514871208e9c8fb6e03bcb5102d57a3a", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "4644a9efa48a4093260496726780ec169c968b13df52b701ed2cbb6e02e31595", + "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": "f3ba2e0f12f2430a468fe94371ada76430146a7b100b36a4bfaef2286b58f942", + "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": "73c3da00eb6f182f8de88249ede9909323ac4589", + "source_completion_sha256": "9e6333d4f0b5a404dd29f4a81265da83fc039e23f3eddebf268e68922e393876", + "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__w7li32jt", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "d8801b5927f4abed792214aa78675717ae8cbf5e323da7c54aa6d5aba0c14eba", + "is_fork": true, + "learner_path": "tasks/db5508c81fcf89c863c5fc8f/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/73c3da00eb6f182f8de88249ede9909323ac4589/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": "7408056292d88fb8bc14ff736ae89d8fef0601f5542f79f2216162d178da76c5", + "provenance_path": "tasks/db5508c81fcf89c863c5fc8f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "73c3da00eb6f182f8de88249ede9909323ac4589", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f06b8f272c4034c208db58e0d1a2945faa655446", + "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__w7li32jt", + "task_sha256": "62535c781efc1c07acf4c1a1436593601387fad6ca90525859f2945876e9c1f4", + "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__w7li32jt", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/instruction.md b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..777fca49644099bbe1863b3a5d0739f02d06274e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/instruction.md @@ -0,0 +1,32 @@ +Text styling functions produce inverted colors and styles + +#### Description + +The `click.style()` function is producing inverted colors and styles. When trying to style text with foreground colors, it applies background colors instead, and vice versa. Additionally, boolean style parameters like `bold`, `italic`, etc. are applying the opposite effect - when `True` is passed, it applies the "off" code, and when `False` is passed, it applies the "on" code. + +#### Steps/Code to Reproduce + +```python +import click + +# This should make text red, but makes background red instead +styled = click.style('hello', fg='red') +print(repr(styled)) # Shows background color code instead of foreground + +# This should make background blue, but makes text blue instead +styled = click.style('hello', bg='blue') +print(repr(styled)) # Shows foreground color code instead of background + +# This should make text bold, but removes bold formatting +styled = click.style('hello', bold=True) +print(repr(styled)) # Shows bold-off code (22) instead of bold-on code (1) + +# Using secho also affected +click.secho('test message', fg='green') # Wrong colors displayed +``` + +The issue also affects the `secho` function and any other styling functionality that relies on the `style` function internally. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/metadata.json b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..6c2aa8ec58cc0cc6ecf212555d686fcf8678815c --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/metadata.json @@ -0,0 +1,744 @@ +{ + "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_commands.py::test_deprecated_in_invocation", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_testing.py::test_with_color", + "tests/test_testing.py::test_with_color_errors", + "tests/test_utils.py::test_echo_color_flag" + ], + "PASS_TO_PASS": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_name", + "tests/test_commands.py::test_unprocessed_options", + "tests/test_commands.py::test_deprecated_in_help_messages[None]", + "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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_secho", + "tests/test_termui.py::test_progressbar_yields_all_items", + "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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_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_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-00.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", + "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_prompts", + "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_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", + "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_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_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", + "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": "f06b8f272c4034c208db58e0d1a2945faa655446", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "73c3da00eb6f182f8de88249ede9909323ac4589" + }, + "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_arguments.py", + "/testbed/tests/test_basic.py", + "/testbed/tests/test_chain.py", + "/testbed/tests/test_command_decorators.py", + "/testbed/tests/test_compat.py", + "/testbed/tests/test_context.py", + "/testbed/tests/test_defaults.py", + "/testbed/tests/test_formatting.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_normalization.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_shell_completion.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_commands.py", + "tests/test_custom_classes.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/termui.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2777927, + "task_id": "pallets__click.fde47b4b.combine_file__w7li32jt", + "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__w7li32jt", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "d8801b5927f4abed792214aa78675717ae8cbf5e323da7c54aa6d5aba0c14eba", + "is_fork": true, + "learner_path": "tasks/db5508c81fcf89c863c5fc8f/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/73c3da00eb6f182f8de88249ede9909323ac4589/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": "7408056292d88fb8bc14ff736ae89d8fef0601f5542f79f2216162d178da76c5", + "provenance_path": "tasks/db5508c81fcf89c863c5fc8f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "73c3da00eb6f182f8de88249ede9909323ac4589", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f06b8f272c4034c208db58e0d1a2945faa655446", + "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__w7li32jt", + "task_sha256": "62535c781efc1c07acf4c1a1436593601387fad6ca90525859f2945876e9c1f4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/provenance.json b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d854d5cd1e132284b95694a43d88be0c39adee5e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "8f488b4afe7191d5fd5b058785050e3c514871208e9c8fb6e03bcb5102d57a3a", + "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/73c3da00eb6f182f8de88249ede9909323ac4589/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "9e6333d4f0b5a404dd29f4a81265da83fc039e23f3eddebf268e68922e393876", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "7c92aa08d31b7876c9e3bb200e7df8d1b8281f74f9f778fccea3ba406bc22424", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__w7li32jt", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "d8801b5927f4abed792214aa78675717ae8cbf5e323da7c54aa6d5aba0c14eba", + "is_fork": true, + "learner_path": "tasks/db5508c81fcf89c863c5fc8f/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/73c3da00eb6f182f8de88249ede9909323ac4589/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": "7408056292d88fb8bc14ff736ae89d8fef0601f5542f79f2216162d178da76c5", + "provenance_path": "tasks/db5508c81fcf89c863c5fc8f/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "73c3da00eb6f182f8de88249ede9909323ac4589", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f06b8f272c4034c208db58e0d1a2945faa655446", + "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__w7li32jt", + "task_sha256": "62535c781efc1c07acf4c1a1436593601387fad6ca90525859f2945876e9c1f4", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..9a64614ff93d9feb251517231b5792cb4df0cffd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/provided-gold.diff @@ -0,0 +1,146 @@ +diff --git a/src/click/termui.py b/src/click/termui.py +index 6aafa58a31df2bd5a538ddf204f024201a52fd83..d30dc1976df31db100c895cc2a24910dffa17647 100644 +--- a/src/click/termui.py ++++ b/src/click/termui.py +@@ -523,6 +523,82 @@ + strikethrough: bool | None = None, + reset: bool = True, + ) -> str: ++ """Styles a text with ANSI styles and returns the new string. By ++ default the styling is self contained which means that at the end ++ of the string a reset code is issued. This can be prevented by ++ passing ``reset=False``. ++ ++ Examples:: ++ ++ click.echo(click.style('Hello World!', fg='green')) ++ click.echo(click.style('ATTENTION!', blink=True)) ++ click.echo(click.style('Some things', reverse=True, fg='cyan')) ++ click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) ++ ++ Supported color names: ++ ++ * ``black`` (might be a gray) ++ * ``red`` ++ * ``green`` ++ * ``yellow`` (might be an orange) ++ * ``blue`` ++ * ``magenta`` ++ * ``cyan`` ++ * ``white`` (might be light gray) ++ * ``bright_black`` ++ * ``bright_red`` ++ * ``bright_green`` ++ * ``bright_yellow`` ++ * ``bright_blue`` ++ * ``bright_magenta`` ++ * ``bright_cyan`` ++ * ``bright_white`` ++ * ``reset`` (reset the color code only) ++ ++ If the terminal supports it, color may also be specified as: ++ ++ - An integer in the interval [0, 255]. The terminal must support ++ 8-bit/256-color mode. ++ - An RGB tuple of three integers in [0, 255]. The terminal must ++ support 24-bit/true-color mode. ++ ++ See https://en.wikipedia.org/wiki/ANSI_color and ++ https://gist.github.com/XVilka/8346728 for more information. ++ ++ :param text: the string to style with ansi codes. ++ :param fg: if provided this will become the foreground color. ++ :param bg: if provided this will become the background color. ++ :param bold: if provided this will enable or disable bold mode. ++ :param dim: if provided this will enable or disable dim mode. This is ++ badly supported. ++ :param underline: if provided this will enable or disable underline. ++ :param overline: if provided this will enable or disable overline. ++ :param italic: if provided this will enable or disable italic. ++ :param blink: if provided this will enable or disable blinking. ++ :param reverse: if provided this will enable or disable inverse ++ rendering (foreground becomes background and the ++ other way round). ++ :param strikethrough: if provided this will enable or disable ++ striking through text. ++ :param reset: by default a reset-all code is added at the end of the ++ string which means that styles do not carry over. This ++ can be disabled to compose styles. ++ ++ .. versionchanged:: 8.0 ++ A non-string ``message`` is converted to a string. ++ ++ .. versionchanged:: 8.0 ++ Added support for 256 and RGB color codes. ++ ++ .. versionchanged:: 8.0 ++ Added the ``strikethrough``, ``italic``, and ``overline`` ++ parameters. ++ ++ .. versionchanged:: 7.0 ++ Added support for bright colors. ++ ++ .. versionadded:: 2.0 ++ """ + if not isinstance(text, str): + text = str(text) + +@@ -530,34 +606,34 @@ + + if fg: + try: +- bits.append(f"\033[{_interpret_color(bg)}m") ++ bits.append(f"\033[{_interpret_color(fg)}m") + except KeyError: + raise TypeError(f"Unknown color {fg!r}") from None + + if bg: + try: +- bits.append(f"\033[{_interpret_color(fg, 10)}m") ++ bits.append(f"\033[{_interpret_color(bg, 10)}m") + except KeyError: + raise TypeError(f"Unknown color {bg!r}") from None + + if bold is not None: +- bits.append(f"\033[{22 if bold else 1}m") ++ bits.append(f"\033[{1 if bold else 22}m") + if dim is not None: +- bits.append(f"\033[{22 if dim else 2}m") ++ bits.append(f"\033[{2 if dim else 22}m") + if underline is not None: +- bits.append(f"\033[{24 if underline else 4}m") ++ bits.append(f"\033[{4 if underline else 24}m") + if overline is not None: +- bits.append(f"\033[{55 if overline else 53}m") ++ bits.append(f"\033[{53 if overline else 55}m") + if italic is not None: +- bits.append(f"\033[{23 if italic else 3}m") ++ bits.append(f"\033[{3 if italic else 23}m") + if blink is not None: +- bits.append(f"\033[{25 if blink else 5}m") ++ bits.append(f"\033[{5 if blink else 25}m") + if reverse is not None: +- bits.append(f"\033[{27 if reverse else 7}m") ++ bits.append(f"\033[{7 if reverse else 27}m") + if strikethrough is not None: +- bits.append(f"\033[{29 if strikethrough else 9}m") ++ bits.append(f"\033[{9 if strikethrough else 29}m") + bits.append(text) +- if not reset: ++ if reset: + bits.append(_ansi_reset_all) + return "".join(bits) + +@@ -602,10 +678,10 @@ + + .. versionadded:: 2.0 + """ +- if message is not None and isinstance(message, (bytes, bytearray)): ++ if message is not None and not isinstance(message, (bytes, bytearray)): + message = style(message, **styles) + +- return echo(message, file=file, nl=nl, color=not color, err=not err) ++ return echo(message, file=file, nl=nl, err=err, color=color) + + + @t.overload diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4ff0d587c0333bc946a0daa41ed5814f9fa6c31d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/solution/solve.sh @@ -0,0 +1,152 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/termui.py b/src/click/termui.py +index 6aafa58a31df2bd5a538ddf204f024201a52fd83..d30dc1976df31db100c895cc2a24910dffa17647 100644 +--- a/src/click/termui.py ++++ b/src/click/termui.py +@@ -523,6 +523,82 @@ + strikethrough: bool | None = None, + reset: bool = True, + ) -> str: ++ """Styles a text with ANSI styles and returns the new string. By ++ default the styling is self contained which means that at the end ++ of the string a reset code is issued. This can be prevented by ++ passing ``reset=False``. ++ ++ Examples:: ++ ++ click.echo(click.style('Hello World!', fg='green')) ++ click.echo(click.style('ATTENTION!', blink=True)) ++ click.echo(click.style('Some things', reverse=True, fg='cyan')) ++ click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) ++ ++ Supported color names: ++ ++ * ``black`` (might be a gray) ++ * ``red`` ++ * ``green`` ++ * ``yellow`` (might be an orange) ++ * ``blue`` ++ * ``magenta`` ++ * ``cyan`` ++ * ``white`` (might be light gray) ++ * ``bright_black`` ++ * ``bright_red`` ++ * ``bright_green`` ++ * ``bright_yellow`` ++ * ``bright_blue`` ++ * ``bright_magenta`` ++ * ``bright_cyan`` ++ * ``bright_white`` ++ * ``reset`` (reset the color code only) ++ ++ If the terminal supports it, color may also be specified as: ++ ++ - An integer in the interval [0, 255]. The terminal must support ++ 8-bit/256-color mode. ++ - An RGB tuple of three integers in [0, 255]. The terminal must ++ support 24-bit/true-color mode. ++ ++ See https://en.wikipedia.org/wiki/ANSI_color and ++ https://gist.github.com/XVilka/8346728 for more information. ++ ++ :param text: the string to style with ansi codes. ++ :param fg: if provided this will become the foreground color. ++ :param bg: if provided this will become the background color. ++ :param bold: if provided this will enable or disable bold mode. ++ :param dim: if provided this will enable or disable dim mode. This is ++ badly supported. ++ :param underline: if provided this will enable or disable underline. ++ :param overline: if provided this will enable or disable overline. ++ :param italic: if provided this will enable or disable italic. ++ :param blink: if provided this will enable or disable blinking. ++ :param reverse: if provided this will enable or disable inverse ++ rendering (foreground becomes background and the ++ other way round). ++ :param strikethrough: if provided this will enable or disable ++ striking through text. ++ :param reset: by default a reset-all code is added at the end of the ++ string which means that styles do not carry over. This ++ can be disabled to compose styles. ++ ++ .. versionchanged:: 8.0 ++ A non-string ``message`` is converted to a string. ++ ++ .. versionchanged:: 8.0 ++ Added support for 256 and RGB color codes. ++ ++ .. versionchanged:: 8.0 ++ Added the ``strikethrough``, ``italic``, and ``overline`` ++ parameters. ++ ++ .. versionchanged:: 7.0 ++ Added support for bright colors. ++ ++ .. versionadded:: 2.0 ++ """ + if not isinstance(text, str): + text = str(text) + +@@ -530,34 +606,34 @@ + + if fg: + try: +- bits.append(f"\033[{_interpret_color(bg)}m") ++ bits.append(f"\033[{_interpret_color(fg)}m") + except KeyError: + raise TypeError(f"Unknown color {fg!r}") from None + + if bg: + try: +- bits.append(f"\033[{_interpret_color(fg, 10)}m") ++ bits.append(f"\033[{_interpret_color(bg, 10)}m") + except KeyError: + raise TypeError(f"Unknown color {bg!r}") from None + + if bold is not None: +- bits.append(f"\033[{22 if bold else 1}m") ++ bits.append(f"\033[{1 if bold else 22}m") + if dim is not None: +- bits.append(f"\033[{22 if dim else 2}m") ++ bits.append(f"\033[{2 if dim else 22}m") + if underline is not None: +- bits.append(f"\033[{24 if underline else 4}m") ++ bits.append(f"\033[{4 if underline else 24}m") + if overline is not None: +- bits.append(f"\033[{55 if overline else 53}m") ++ bits.append(f"\033[{53 if overline else 55}m") + if italic is not None: +- bits.append(f"\033[{23 if italic else 3}m") ++ bits.append(f"\033[{3 if italic else 23}m") + if blink is not None: +- bits.append(f"\033[{25 if blink else 5}m") ++ bits.append(f"\033[{5 if blink else 25}m") + if reverse is not None: +- bits.append(f"\033[{27 if reverse else 7}m") ++ bits.append(f"\033[{7 if reverse else 27}m") + if strikethrough is not None: +- bits.append(f"\033[{29 if strikethrough else 9}m") ++ bits.append(f"\033[{9 if strikethrough else 29}m") + bits.append(text) +- if not reset: ++ if reset: + bits.append(_ansi_reset_all) + return "".join(bits) + +@@ -602,10 +678,10 @@ + + .. versionadded:: 2.0 + """ +- if message is not None and isinstance(message, (bytes, bytearray)): ++ if message is not None and not isinstance(message, (bytes, bytearray)): + message = style(message, **styles) + +- return echo(message, file=file, nl=nl, color=not color, err=not err) ++ return echo(message, file=file, nl=nl, err=err, color=color) + + + @t.overload +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/task.toml b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..fc417c0802520bb999172fc3c09f919c557e4431 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "fail-to-pass": [ + "tests/test_commands.py::test_deprecated_in_invocation", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_testing.py::test_with_color", + "tests/test_testing.py::test_with_color_errors", + "tests/test_utils.py::test_echo_color_flag" + ], + "pass-to-pass": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_name", + "tests/test_commands.py::test_unprocessed_options", + "tests/test_commands.py::test_deprecated_in_help_messages[None]", + "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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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_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_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_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_secho", + "tests/test_termui.py::test_progressbar_yields_all_items", + "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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_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_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-00.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", + "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_prompts", + "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_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", + "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_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_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", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..8aaf6a2a593030eedcfd158522c0fd8815b82a81 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/canaries/first-hunk-only.sh @@ -0,0 +1,93 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/termui.py b/src/click/termui.py +index 6aafa58a31df2bd5a538ddf204f024201a52fd83..d30dc1976df31db100c895cc2a24910dffa17647 100644 +--- a/src/click/termui.py ++++ b/src/click/termui.py +@@ -523,6 +523,82 @@ + strikethrough: bool | None = None, + reset: bool = True, + ) -> str: ++ """Styles a text with ANSI styles and returns the new string. By ++ default the styling is self contained which means that at the end ++ of the string a reset code is issued. This can be prevented by ++ passing ``reset=False``. ++ ++ Examples:: ++ ++ click.echo(click.style('Hello World!', fg='green')) ++ click.echo(click.style('ATTENTION!', blink=True)) ++ click.echo(click.style('Some things', reverse=True, fg='cyan')) ++ click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) ++ ++ Supported color names: ++ ++ * ``black`` (might be a gray) ++ * ``red`` ++ * ``green`` ++ * ``yellow`` (might be an orange) ++ * ``blue`` ++ * ``magenta`` ++ * ``cyan`` ++ * ``white`` (might be light gray) ++ * ``bright_black`` ++ * ``bright_red`` ++ * ``bright_green`` ++ * ``bright_yellow`` ++ * ``bright_blue`` ++ * ``bright_magenta`` ++ * ``bright_cyan`` ++ * ``bright_white`` ++ * ``reset`` (reset the color code only) ++ ++ If the terminal supports it, color may also be specified as: ++ ++ - An integer in the interval [0, 255]. The terminal must support ++ 8-bit/256-color mode. ++ - An RGB tuple of three integers in [0, 255]. The terminal must ++ support 24-bit/true-color mode. ++ ++ See https://en.wikipedia.org/wiki/ANSI_color and ++ https://gist.github.com/XVilka/8346728 for more information. ++ ++ :param text: the string to style with ansi codes. ++ :param fg: if provided this will become the foreground color. ++ :param bg: if provided this will become the background color. ++ :param bold: if provided this will enable or disable bold mode. ++ :param dim: if provided this will enable or disable dim mode. This is ++ badly supported. ++ :param underline: if provided this will enable or disable underline. ++ :param overline: if provided this will enable or disable overline. ++ :param italic: if provided this will enable or disable italic. ++ :param blink: if provided this will enable or disable blinking. ++ :param reverse: if provided this will enable or disable inverse ++ rendering (foreground becomes background and the ++ other way round). ++ :param strikethrough: if provided this will enable or disable ++ striking through text. ++ :param reset: by default a reset-all code is added at the end of the ++ string which means that styles do not carry over. This ++ can be disabled to compose styles. ++ ++ .. versionchanged:: 8.0 ++ A non-string ``message`` is converted to a string. ++ ++ .. versionchanged:: 8.0 ++ Added support for 256 and RGB color codes. ++ ++ .. versionchanged:: 8.0 ++ Added the ``strikethrough``, ``italic``, and ``overline`` ++ parameters. ++ ++ .. versionchanged:: 7.0 ++ Added support for bright colors. ++ ++ .. versionadded:: 2.0 ++ """ + if not isinstance(text, str): + text = str(text) + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_file__w7li32jt/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/adapter.json b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f00acd74ebde395e5a27165bd5b15d8615b38761 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "7317d01bfc72bf13aa18fccc47c2a596b7ff953adc6ba7afebfcafdae02c9dd8", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "19a133da8f5a17bc7ad624d77241f7046dc8c5b5b46142732246616ae0aefe42", + "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": "94b9ace133d88732a5d673ea61e07206d08072c63679dec94673b5ab5d21c997", + "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": "b6c0dd38a875ed5c234d1259918012788ca7c7eb", + "source_completion_sha256": "3f427ea4b3b0a309d0ed3271b3f0db1202639444ea2c38e146ce8a95659d8928", + "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_module__07m8lbbv", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "0045f649d023df55e8a9a064eb408389ddd084d48a63a6beeeba4c13b3376a4a", + "is_fork": true, + "learner_path": "tasks/5ebefb6a63dac28329bb3778/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/b6c0dd38a875ed5c234d1259918012788ca7c7eb/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": "2ebb7e282b35de4802622480686afc6efb9f4203b41e5a22e509e81d586bffe8", + "provenance_path": "tasks/5ebefb6a63dac28329bb3778/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b6c0dd38a875ed5c234d1259918012788ca7c7eb", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "9ca47022bba0c8e62fe26e581ebf18c4e5b21985", + "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_module__07m8lbbv", + "task_sha256": "5413251bb77a5409085891e9563c1f2f94caf4b8bfddb02134562556dfee7690", + "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_module__07m8lbbv", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/instruction.md b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdc95d2a298c7c5a1cb2c9e646044820d8d4d983 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/instruction.md @@ -0,0 +1,36 @@ +Shell completion broken after recent changes + +#### Description + +Shell completion is not working properly. When trying to complete commands, options, or arguments, the completion system returns empty results or incorrect suggestions. + +#### Steps/Code to Reproduce + +```python +import click +from click import Command, Option, Argument, Choice, Path + +# Simple command with options +@click.command() +@click.option('-f', type=click.Path()) +@click.argument('name', type=click.Choice(['test', 'prod'])) +def cli(f, name): + pass + +# Try shell completion - this should suggest options and choices but doesn't work +``` + +When using shell completion (bash/zsh), completions for options like `-f` with path types, choice arguments, and multiple options are not being generated correctly. The completion system appears to be returning empty or incorrect results where it should provide valid completions. + +This affects: +- Path completion for file/directory options +- Choice completion for arguments and options +- Multiple option handling +- Double dash (`--`) handling +- Case sensitive choice completion + +The issue seems to affect the core completion resolution logic that determines what should be completed based on the current context and incomplete input. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/metadata.json b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..58fc8d9181c26c163c9df31a82d72dbf5a8064fe --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/metadata.json @@ -0,0 +1,745 @@ +{ + "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_envvar[2--None]", + "tests/test_basic.py::test_path_option", + "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_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_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_files_closed", + "tests/test_termui.py::test_progressbar_item_show_func" + ], + "PASS_TO_PASS": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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[-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_missing_argument_string_cast", + "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_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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "tests/test_parser.py::test_parser_default_prefixes", + "tests/test_parser.py::test_parser_collects_prefixes", + "tests/test_shell_completion.py::test_chained", + "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_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_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_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_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_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_progressbar_update", + "tests/test_termui.py::test_progressbar_update_with_item_show_func", + "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_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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "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": "9ca47022bba0c8e62fe26e581ebf18c4e5b21985", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "b6c0dd38a875ed5c234d1259918012788ca7c7eb" + }, + "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_chain.py", + "/testbed/tests/test_command_decorators.py", + "/testbed/tests/test_commands.py", + "/testbed/tests/test_compat.py", + "/testbed/tests/test_context.py", + "/testbed/tests/test_custom_classes.py", + "/testbed/tests/test_defaults.py", + "/testbed/tests/test_formatting.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_normalization.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_testing.py", + "/testbed/tests/test_types.py", + "/testbed/tests/test_utils.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_shell_completion.py", + "tests/test_termui.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/shell_completion.py", + "src/click/utils.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2785907, + "task_id": "pallets__click.fde47b4b.combine_module__07m8lbbv", + "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_module__07m8lbbv", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "0045f649d023df55e8a9a064eb408389ddd084d48a63a6beeeba4c13b3376a4a", + "is_fork": true, + "learner_path": "tasks/5ebefb6a63dac28329bb3778/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/b6c0dd38a875ed5c234d1259918012788ca7c7eb/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": "2ebb7e282b35de4802622480686afc6efb9f4203b41e5a22e509e81d586bffe8", + "provenance_path": "tasks/5ebefb6a63dac28329bb3778/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b6c0dd38a875ed5c234d1259918012788ca7c7eb", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "9ca47022bba0c8e62fe26e581ebf18c4e5b21985", + "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_module__07m8lbbv", + "task_sha256": "5413251bb77a5409085891e9563c1f2f94caf4b8bfddb02134562556dfee7690", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/provenance.json b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..b0190cc5fb9f51a220833f6a52ae5e88a2fe0c56 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "7317d01bfc72bf13aa18fccc47c2a596b7ff953adc6ba7afebfcafdae02c9dd8", + "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/b6c0dd38a875ed5c234d1259918012788ca7c7eb/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "3f427ea4b3b0a309d0ed3271b3f0db1202639444ea2c38e146ce8a95659d8928", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "5fcff39b917c4dcba130bbc7961a4c81b4cb6c00f55ac66e16426e839a5b3bf3", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_module__07m8lbbv", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "0045f649d023df55e8a9a064eb408389ddd084d48a63a6beeeba4c13b3376a4a", + "is_fork": true, + "learner_path": "tasks/5ebefb6a63dac28329bb3778/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/b6c0dd38a875ed5c234d1259918012788ca7c7eb/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": "2ebb7e282b35de4802622480686afc6efb9f4203b41e5a22e509e81d586bffe8", + "provenance_path": "tasks/5ebefb6a63dac28329bb3778/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b6c0dd38a875ed5c234d1259918012788ca7c7eb", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "9ca47022bba0c8e62fe26e581ebf18c4e5b21985", + "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_module__07m8lbbv", + "task_sha256": "5413251bb77a5409085891e9563c1f2f94caf4b8bfddb02134562556dfee7690", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..c341acbd442a9088d12dcd6458ba2eb97995a991 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/provided-gold.diff @@ -0,0 +1,65 @@ +diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py +index 562957f193515f09c3b80400618bc4eab98fb210..c8655b12aabea2f1f0bb3d36f78ba07ec45df13c 100644 +--- a/src/click/shell_completion.py ++++ b/src/click/shell_completion.py +@@ -601,23 +601,37 @@ + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ ++ # Different shells treat an "=" between a long option name and ++ # value differently. Might keep the value joined, return the "=" ++ # as a separate item, or return the split name and value. Always ++ # split and discard the "=" to make completion easier. + if incomplete == "=": + incomplete = "" +- elif "=" in incomplete or _start_of_option(ctx, incomplete): ++ elif "=" in incomplete and _start_of_option(ctx, incomplete): + name, _, incomplete = incomplete.partition("=") + args.append(name) + +- if "--" not in args and not _start_of_option(ctx, incomplete): ++ # The "--" marker tells Click to stop treating values as options ++ # even if they start with the option character. If it hasn't been ++ # given and the incomplete arg looks like an option, the current ++ # command will provide option name completions. ++ if "--" not in args and _start_of_option(ctx, incomplete): + return ctx.command, incomplete + + params = ctx.command.get_params(ctx) + +- for param in reversed(params): +- if _is_incomplete_option(ctx, args, param): +- return param, incomplete +- ++ # If the last complete arg is an option name with an incomplete ++ # value, the option will provide value completions. + for param in params: + if _is_incomplete_option(ctx, args, param): + return param, incomplete + ++ # It's not an option name or value. The first argument without a ++ # parsed value will provide value completions. ++ for param in params: ++ if _is_incomplete_argument(ctx, param): ++ return param, incomplete ++ ++ # There were no unparsed arguments, the command may be a group that ++ # will provide command name completions. + return ctx.command, incomplete +diff --git a/src/click/utils.py b/src/click/utils.py +index 1ca199de9e9b0d715dd4b77fdfc959186ba9d185..ab2fe5889cee75d559092442696f9b23bf20ebfb 100644 +--- a/src/click/utils.py ++++ b/src/click/utils.py +@@ -38,9 +38,10 @@ + + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: + try: +- return func(args, kwargs) ++ return func(*args, **kwargs) + except Exception: +- return None ++ pass ++ return None + + return update_wrapper(wrapper, func) + diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..810ba90e290c5d1eb4ff22437f1501e8430b7601 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/solution/solve.sh @@ -0,0 +1,71 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py +index 562957f193515f09c3b80400618bc4eab98fb210..c8655b12aabea2f1f0bb3d36f78ba07ec45df13c 100644 +--- a/src/click/shell_completion.py ++++ b/src/click/shell_completion.py +@@ -601,23 +601,37 @@ + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ ++ # Different shells treat an "=" between a long option name and ++ # value differently. Might keep the value joined, return the "=" ++ # as a separate item, or return the split name and value. Always ++ # split and discard the "=" to make completion easier. + if incomplete == "=": + incomplete = "" +- elif "=" in incomplete or _start_of_option(ctx, incomplete): ++ elif "=" in incomplete and _start_of_option(ctx, incomplete): + name, _, incomplete = incomplete.partition("=") + args.append(name) + +- if "--" not in args and not _start_of_option(ctx, incomplete): ++ # The "--" marker tells Click to stop treating values as options ++ # even if they start with the option character. If it hasn't been ++ # given and the incomplete arg looks like an option, the current ++ # command will provide option name completions. ++ if "--" not in args and _start_of_option(ctx, incomplete): + return ctx.command, incomplete + + params = ctx.command.get_params(ctx) + +- for param in reversed(params): +- if _is_incomplete_option(ctx, args, param): +- return param, incomplete +- ++ # If the last complete arg is an option name with an incomplete ++ # value, the option will provide value completions. + for param in params: + if _is_incomplete_option(ctx, args, param): + return param, incomplete + ++ # It's not an option name or value. The first argument without a ++ # parsed value will provide value completions. ++ for param in params: ++ if _is_incomplete_argument(ctx, param): ++ return param, incomplete ++ ++ # There were no unparsed arguments, the command may be a group that ++ # will provide command name completions. + return ctx.command, incomplete +diff --git a/src/click/utils.py b/src/click/utils.py +index 1ca199de9e9b0d715dd4b77fdfc959186ba9d185..ab2fe5889cee75d559092442696f9b23bf20ebfb 100644 +--- a/src/click/utils.py ++++ b/src/click/utils.py +@@ -38,9 +38,10 @@ + + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: + try: +- return func(args, kwargs) ++ return func(*args, **kwargs) + except Exception: +- return None ++ pass ++ return None + + return update_wrapper(wrapper, func) + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/task.toml b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..ab5ea7721138983630f5aee42f3227f4d68c14af --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "fail-to-pass": [ + "tests/test_arguments.py::test_nargs_envvar[2--None]", + "tests/test_basic.py::test_path_option", + "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_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_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_files_closed", + "tests/test_termui.py::test_progressbar_item_show_func" + ], + "pass-to-pass": [ + "tests/test_arguments.py::test_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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[-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_missing_argument_string_cast", + "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_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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "tests/test_parser.py::test_parser_default_prefixes", + "tests/test_parser.py::test_parser_collects_prefixes", + "tests/test_shell_completion.py::test_chained", + "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_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_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_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_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_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_progressbar_update", + "tests/test_termui.py::test_progressbar_update_with_item_show_func", + "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_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_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-00.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", + "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_prompts", + "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", + "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_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_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", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..846dbe6998330444ee86a375e49591040d27a85a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/canaries/first-hunk-only.sh @@ -0,0 +1,54 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py +index 562957f193515f09c3b80400618bc4eab98fb210..c8655b12aabea2f1f0bb3d36f78ba07ec45df13c 100644 +--- a/src/click/shell_completion.py ++++ b/src/click/shell_completion.py +@@ -601,23 +601,37 @@ + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ ++ # Different shells treat an "=" between a long option name and ++ # value differently. Might keep the value joined, return the "=" ++ # as a separate item, or return the split name and value. Always ++ # split and discard the "=" to make completion easier. + if incomplete == "=": + incomplete = "" +- elif "=" in incomplete or _start_of_option(ctx, incomplete): ++ elif "=" in incomplete and _start_of_option(ctx, incomplete): + name, _, incomplete = incomplete.partition("=") + args.append(name) + +- if "--" not in args and not _start_of_option(ctx, incomplete): ++ # The "--" marker tells Click to stop treating values as options ++ # even if they start with the option character. If it hasn't been ++ # given and the incomplete arg looks like an option, the current ++ # command will provide option name completions. ++ if "--" not in args and _start_of_option(ctx, incomplete): + return ctx.command, incomplete + + params = ctx.command.get_params(ctx) + +- for param in reversed(params): +- if _is_incomplete_option(ctx, args, param): +- return param, incomplete +- ++ # If the last complete arg is an option name with an incomplete ++ # value, the option will provide value completions. + for param in params: + if _is_incomplete_option(ctx, args, param): + return param, incomplete + ++ # It's not an option name or value. The first argument without a ++ # parsed value will provide value completions. ++ for param in params: ++ if _is_incomplete_argument(ctx, param): ++ return param, incomplete ++ ++ # There were no unparsed arguments, the command may be a group that ++ # will provide command name completions. + return ctx.command, incomplete +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__07m8lbbv/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/LICENSE.source b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/LICENSE.source @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/adapter.json b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..3d0ffaf8c896ac9064addee0504369d3b049fed1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/adapter.json @@ -0,0 +1,127 @@ +{ + "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": "aba3065226991f95034fc7ba3ab5f728725b75f143c4e354733fe8d6a1e19654", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "3de482306441a3b214b49183838dfe4dc2ac4e61dd9fa2fa806422a643f3d7a9", + "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": "c2f9de267605d215ddef6a09f678c76a74795c60dfdd2cd23bb636effb58a92c", + "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": "032ff40576470fad7422931b75c42f1d8c61af1e", + "source_completion_sha256": "157be0b49e00d7f8e6e3dfb6971c1707fdc8e4b2f537c34766755cf0d919d26a", + "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_module__2aky5qvj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "b7517e6e4af8e56ab4e5ff3bbd517df7bd3d07140d88ec33fc4e0ce1d0941d71", + "is_fork": true, + "learner_path": "tasks/5da583f7143d6d6eb6457540/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/032ff40576470fad7422931b75c42f1d8c61af1e/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": "53769dd666e5ea391ae5352ec5efb36a3db41f6db95c9d70409953ede0dea5d4", + "provenance_path": "tasks/5da583f7143d6d6eb6457540/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "032ff40576470fad7422931b75c42f1d8c61af1e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d21a58efe6995532d4bc8b4bbc019afb545c65b1", + "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_module__2aky5qvj", + "task_sha256": "476d3679cf0839f7c1574be8a6b07def7c0243fd2642266011856a05ab0d50e4", + "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_module__2aky5qvj", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "pallets/click" +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/dependency-setup.sh b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a758f4322274733a1ba991aef0ce3af579c572f2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -r requirements/tests.txt diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/environment/Dockerfile b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/instruction.md b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0270b2ad9626fa1ec2a225eada77830812b86b6 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/instruction.md @@ -0,0 +1,33 @@ +open_file function returns undefined variable causing UnboundLocalError + +#### Description + +The `open_file` function in `click.utils` is returning an undefined variable `f` before it's properly assigned, causing `UnboundLocalError` when trying to open files. + +#### Steps/Code to Reproduce + +```python +import click + +# This will raise UnboundLocalError +with click.open_file('test.txt', 'w') as f: + f.write('hello') +``` + +The error occurs because the function tries to return `f` before the variable is defined in the function scope. + +#### Expected Behavior + +The function should properly open and return a file handle without raising `UnboundLocalError`. + +#### Actual Behavior + +``` +UnboundLocalError: local variable 'f' referenced before assignment +``` + +This affects any usage of `click.open_file()` including atomic file operations and various encoding scenarios. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/metadata.json b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..de12175e2dd099c46cf4e266ede924e11141c29a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/metadata.json @@ -0,0 +1,745 @@ +{ + "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_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_context_settings", + "tests/test_utils.py::test_open_file", + "tests/test_utils.py::test_open_file_ignore_errors_stdin", + "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_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_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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[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_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_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_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_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_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_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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_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-00.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", + "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_prompts", + "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_pathlib_dash", + "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": "d21a58efe6995532d4bc8b4bbc019afb545c65b1", + "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", + "learner": "032ff40576470fad7422931b75c42f1d8c61af1e" + }, + "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_arguments.py", + "/testbed/tests/test_basic.py", + "/testbed/tests/test_chain.py", + "/testbed/tests/test_command_decorators.py", + "/testbed/tests/test_commands.py", + "/testbed/tests/test_compat.py", + "/testbed/tests/test_context.py", + "/testbed/tests/test_custom_classes.py", + "/testbed/tests/test_defaults.py", + "/testbed/tests/test_formatting.py", + "/testbed/tests/test_imports.py", + "/testbed/tests/test_info_dict.py", + "/testbed/tests/test_normalization.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_parser.py", + "/testbed/tests/test_termui.py", + "/testbed/tests/test_testing.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_shell_completion.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/shell_completion.py", + "src/click/utils.py" + ], + "source_repo": "swesmith/pallets__click.fde47b4b", + "source_stages_bytes": 2809143, + "task_id": "pallets__click.fde47b4b.combine_module__2aky5qvj", + "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_module__2aky5qvj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "b7517e6e4af8e56ab4e5ff3bbd517df7bd3d07140d88ec33fc4e0ce1d0941d71", + "is_fork": true, + "learner_path": "tasks/5da583f7143d6d6eb6457540/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/032ff40576470fad7422931b75c42f1d8c61af1e/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": "53769dd666e5ea391ae5352ec5efb36a3db41f6db95c9d70409953ede0dea5d4", + "provenance_path": "tasks/5da583f7143d6d6eb6457540/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "032ff40576470fad7422931b75c42f1d8c61af1e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d21a58efe6995532d4bc8b4bbc019afb545c65b1", + "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_module__2aky5qvj", + "task_sha256": "476d3679cf0839f7c1574be8a6b07def7c0243fd2642266011856a05ab0d50e4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "pallets/click", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/provenance.json b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..26d4bda199a989d786c954171d0ce5b3e982964a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "aba3065226991f95034fc7ba3ab5f728725b75f143c4e354733fe8d6a1e19654", + "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/032ff40576470fad7422931b75c42f1d8c61af1e/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "157be0b49e00d7f8e6e3dfb6971c1707fdc8e4b2f537c34766755cf0d919d26a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "8b8245bc973dff61e32a063f80d3f62768b4ab589df62b9fc076ec55760ff612", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_module__2aky5qvj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", + "instruction_sha256": "b7517e6e4af8e56ab4e5ff3bbd517df7bd3d07140d88ec33fc4e0ce1d0941d71", + "is_fork": true, + "learner_path": "tasks/5da583f7143d6d6eb6457540/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/032ff40576470fad7422931b75c42f1d8c61af1e/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": "53769dd666e5ea391ae5352ec5efb36a3db41f6db95c9d70409953ede0dea5d4", + "provenance_path": "tasks/5da583f7143d6d6eb6457540/source-proof.json", + "repository_lineage": [ + "swesmith/pallets__click.fde47b4b", + "pallets/click" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "032ff40576470fad7422931b75c42f1d8c61af1e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d21a58efe6995532d4bc8b4bbc019afb545c65b1", + "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_module__2aky5qvj", + "task_sha256": "476d3679cf0839f7c1574be8a6b07def7c0243fd2642266011856a05ab0d50e4", + "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" +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/provided-gold.diff b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..58bcf57cc6a8d2a133282e1d03bd13b9c675c177 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/provided-gold.diff @@ -0,0 +1,36 @@ +diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py +index 6a96ed3bfd107c773286fd8d8c38a78b11c92dd2..c8655b12aabea2f1f0bb3d36f78ba07ec45df13c 100644 +--- a/src/click/shell_completion.py ++++ b/src/click/shell_completion.py +@@ -344,7 +344,7 @@ + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: +- return f"{item.value},{item.type.lower()}" ++ return f"{item.type},{item.value}" + + + class ZshComplete(ShellComplete): +diff --git a/src/click/utils.py b/src/click/utils.py +index 144b9fbd90d8bf6f0c0be10feb57704ec7f539a1..ab2fe5889cee75d559092442696f9b23bf20ebfb 100644 +--- a/src/click/utils.py ++++ b/src/click/utils.py +@@ -391,8 +391,6 @@ + + .. versionadded:: 3.0 + """ +- +- return f + if lazy: + return t.cast( + "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic) +@@ -402,6 +400,9 @@ + + if not should_close: + f = t.cast("t.IO[t.Any]", KeepOpenFile(f)) ++ ++ return f ++ + + def format_filename( + filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/solution/solve.sh b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..50deba0efc119855bf1f6a5163709f080cbdc993 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/solution/solve.sh @@ -0,0 +1,42 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py +index 6a96ed3bfd107c773286fd8d8c38a78b11c92dd2..c8655b12aabea2f1f0bb3d36f78ba07ec45df13c 100644 +--- a/src/click/shell_completion.py ++++ b/src/click/shell_completion.py +@@ -344,7 +344,7 @@ + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: +- return f"{item.value},{item.type.lower()}" ++ return f"{item.type},{item.value}" + + + class ZshComplete(ShellComplete): +diff --git a/src/click/utils.py b/src/click/utils.py +index 144b9fbd90d8bf6f0c0be10feb57704ec7f539a1..ab2fe5889cee75d559092442696f9b23bf20ebfb 100644 +--- a/src/click/utils.py ++++ b/src/click/utils.py +@@ -391,8 +391,6 @@ + + .. versionadded:: 3.0 + """ +- +- return f + if lazy: + return t.cast( + "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic) +@@ -402,6 +400,9 @@ + + if not should_close: + f = t.cast("t.IO[t.Any]", KeepOpenFile(f)) ++ ++ return f ++ + + def format_filename( + filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/task.toml b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/check_pytest.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/expected-panels.json b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..afb53cf674e428a67094bdd09ead186d82df8dc7 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/expected-panels.json @@ -0,0 +1,485 @@ +{ + "fail-to-pass": [ + "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_context_settings", + "tests/test_utils.py::test_open_file", + "tests/test_utils.py::test_open_file_ignore_errors_stdin", + "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_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_nargs_star", + "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", + "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_missing_argument_string_cast", + "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_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_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_basic.py::test_help_invalid_default", + "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_command_no_args_is_help", + "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_group_add_command_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_compat.py::test_is_jupyter_kernel_output", + "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_make_pass_meta_decorator_doc", + "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_with_resource", + "tests/test_context.py::test_make_pass_decorator_args", + "tests/test_context.py::test_propagate_show_default_setting", + "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_context.py::test_propagate_opt_prefixes", + "tests/test_custom_classes.py::test_command_context_class", + "tests/test_custom_classes.py::test_context_invoke_type", + "tests/test_custom_classes.py::test_context_formatter_class", + "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_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_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_invalid_option", + "tests/test_options.py::test_invalid_nargs", + "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_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_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_multiple_default_type", + "tests/test_options.py::test_multiple_default_composite_type", + "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_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=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_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_option_string_cast", + "tests/test_options.py::test_missing_required_flag", + "tests/test_options.py::test_missing_choice", + "tests/test_options.py::test_missing_envvar", + "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_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_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_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_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", + "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", + "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[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_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_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_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_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_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_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_progress_bar_update_min_steps", + "tests/test_termui.py::test_fast_edit", + "tests/test_termui.py::test_edit", + "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_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-00.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", + "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_prompts", + "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_pathlib_dash", + "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]" + ] +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/grade.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/panel-config.json b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa43ac9655f92f387315102bc01e522ca6afa9a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "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" + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/test.sh b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted-inventory.json b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..f128f5129ca2e77d1161427cc83e6bd5c03efc46 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted-inventory.json @@ -0,0 +1,167 @@ +{ + "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" + } + } +} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/pyproject.toml b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f3655c9a35cbb7e3ccd91021c3f57971a37f7e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/pyproject.toml @@ -0,0 +1,102 @@ +[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 = true +source = ["click", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.mypy] +python_version = "3.8" +files = ["src/click", "tests/typing"] +show_error_codes = true +pretty = true +strict = 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 = true +show-fixes = true +output-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 = true +order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/conftest.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9440804feb3b22cb4a28f1f9eaa7f6e1fb0ce049 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def runner(request): + return CliRunner() diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_arguments.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc56a468b18424fbb479871acd74c32b0da519d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_arguments.py @@ -0,0 +1,436 @@ +import sys +from 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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_basic.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d68b96299b9b3219f33f2bcb1cafaaacc6a24dc9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_basic.py @@ -0,0 +1,575 @@ +import os +from 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) == "" + assert repr(group) == "" + assert repr(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.output diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_chain.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..702eaaa3e18edae197ec563497500cfb595f8441 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_chain.py @@ -0,0 +1,245 @@ +import 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.xfail +def 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="] diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_command_decorators.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_command_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd268c0a60be62ed5b8d667d61ac35bc4c2a6b8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_command_decorators.py @@ -0,0 +1,92 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_commands.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..02c4a30438ac38245b0917b43b293855fee45c5d --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_commands.py @@ -0,0 +1,407 @@ +import 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!",) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_compat.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2e424cb2a18694aed3f71126d2dec2b9618f66 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_compat.py @@ -0,0 +1,10 @@ +from 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()) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_context.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd618bd4590a0bc4b500ce5937a788135e02189 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_context.py @@ -0,0 +1,545 @@ +import logging +from contextlib import contextmanager + +import pytest + +import click +from click import Context +from click import Option +from click import Parameter +from click.core import ParameterSource +from click.decorators import help_option +from 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 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 == {"-", "--", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_custom_classes.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_custom_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..314842bdace76c0c0a17ff34553a3d66bcfa3856 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_custom_classes.py @@ -0,0 +1,112 @@ +import 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 CustomGroup diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_defaults.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..3f293e881626a1c578eb2071cff929124394bfd1 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_defaults.py @@ -0,0 +1,86 @@ +import 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_formatting.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7e7bad1f7e0b2e414f76a2f7486ae37d7098b5 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_formatting.py @@ -0,0 +1,368 @@ +import 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 == expected diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_imports.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..39dfbdbc24ac7d2b8c5c1f7b27e76b7acb52e19e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_imports.py @@ -0,0 +1,69 @@ +import json +import subprocess +import 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 rv +builtins.__import__ = tracking_import + +import click +rv = list(found_imports) +import json +click.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_IMPORTS diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_info_dict.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_info_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..79d39ee513011d689f3bfc9f2bec3d0c8c1f5dd8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_info_dict.py @@ -0,0 +1,275 @@ +import 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": "", + "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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_normalization.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..502e654a3774a159ddf20596d0036d65dd633110 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_normalization.py @@ -0,0 +1,38 @@ +import 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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_options.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3b69287554642271452f12e093b28711a60eda --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_options.py @@ -0,0 +1,1017 @@ +import os +import re + +import pytest + +import click +from 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=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, []) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_parser.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3ad5931761ad0da0b4d3d8b7481bfd5f89ebb --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_parser.py @@ -0,0 +1,32 @@ +import pytest + +import click +from click.parser import _OptionParser +from 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 == {"-", "--", "+", "!"} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_shell_completion.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..3511f0743ab7100aa565b4f37d4f1ae75b9c7501 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_shell_completion.py @@ -0,0 +1,442 @@ +import warnings + +import pytest + +import click.shell_completion +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import add_completion_class +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from 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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_termui.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_termui.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d0a66c2e58b8c604031f7689151b1ecf0090e --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_termui.py @@ -0,0 +1,487 @@ +import platform +import tempfile +import time + +import pytest + +import click._termui_impl +from 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.output diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_testing.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2d512ab9844f9ce9a131cad2e01e663d908e73 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_testing.py @@ -0,0 +1,430 @@ +import os +import sys +from io import BytesIO + +import pytest + +import click +from click.exceptions import ClickException +from 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 == "\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" diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_types.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..667953a4775116d6acc05cd178f9485a50cbe3c9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_types.py @@ -0,0 +1,252 @@ +import os.path +import pathlib +import platform +import tempfile + +import pytest + +import click +from 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, "00.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'." diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_utils.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9adab779842cb0993a4b4ba1a4e20ab1ac4cc1b9 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/test_utils.py @@ -0,0 +1,653 @@ +import os +import pathlib +import stat +import sys +from collections import namedtuple +from io import StringIO +from tempfile import tempdir + +import pytest + +import click._termui_impl +import click.utils +from 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 == expect diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_aliased_group.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_aliased_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a1fdac4b22b8ad0d0fb7cbad3d7a09971f9c5b6a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_aliased_group.py @@ -0,0 +1,46 @@ +"""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: + pass diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_confirmation_option.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_confirmation_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a568a6ad06ee0cd33678452843a189bd62348332 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_confirmation_option.py @@ -0,0 +1,14 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_group_kw_options.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_group_kw_options.py new file mode 100644 index 0000000000000000000000000000000000000000..579132facc51c0d0a9c64597204b83149ff34132 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_group_kw_options.py @@ -0,0 +1,11 @@ +from typing_extensions import assert_type + +import click + + +@click.group(context_settings={}) +def hello() -> None: + pass + + +assert_type(hello, click.Group) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_help_option.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_help_option.py new file mode 100644 index 0000000000000000000000000000000000000000..6b822c13147a05f06ccef8b3c0a1c7df2a34cda0 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_help_option.py @@ -0,0 +1,13 @@ +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_options.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_options.py new file mode 100644 index 0000000000000000000000000000000000000000..613e8d43de1eed889dcf171e9538874b122d783b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_options.py @@ -0,0 +1,16 @@ +"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters""" + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.option("--count", default=1, help="number of greetings") +@click.argument("name") +def hello(count: int, name: str) -> None: + for _ in range(count): + click.echo(f"Hello {name}!") + + +assert_type(hello, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_password_option.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_password_option.py new file mode 100644 index 0000000000000000000000000000000000000000..8537e6ff59ec53e94c8adaf5402f46fb646a41c8 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_password_option.py @@ -0,0 +1,14 @@ +import codecs + +from typing_extensions import assert_type + +import click + + +@click.command() +@click.password_option() +def encrypt(password: str) -> None: + click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") + + +assert_type(encrypt, click.Command) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_progressbar.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..98ca1703b6c9194aab0f3926aadf8371cf876f90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_progressbar.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from click import progressbar +from 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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_simple_example.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..641937c5dc65f331de508ea7c23b11d99d479a90 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_simple_example.py @@ -0,0 +1,17 @@ +"""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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_version_option.py b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_version_option.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff37a75fb03f705265a5484dbbf71e81483285a --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tests/typing/typing_version_option.py @@ -0,0 +1,16 @@ +""" +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) diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tox.ini b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5d0d186930d0dac14d2f8b1e54539b1e1aa7dbd2 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/tests/trusted/tox.ini @@ -0,0 +1,55 @@ +[tox] +envlist = + py3{13,12,11,10,9,8} + pypy310 + style + typing + docs +skip_missing_interpreters = true + +[testenv] +package = wheel +wheel_build_env = .pkg +constrain_package_deps = true +use_frozen_constraints = true +deps = -r requirements/tests.txt +commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} + +[testenv:style] +deps = pre-commit +skip_install = true +commands = pre-commit run --all-files + +[testenv:typing] +deps = -r requirements/typing.txt +commands = + mypy + pyright tests/typing + pyright --verifytypes click --ignoreexternal + +[testenv:docs] +deps = -r requirements/docs.txt +commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml + +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + +[testenv:update-requirements] +labels = update +deps = pip-tools +skip_install = true +change_dir = requirements +commands = + 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} diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/canaries/first-hunk-only.sh b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..8dafd844ec179e67f1a7808b83a25d2b7b5fd8e7 --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py +index 6a96ed3bfd107c773286fd8d8c38a78b11c92dd2..c8655b12aabea2f1f0bb3d36f78ba07ec45df13c 100644 +--- a/src/click/shell_completion.py ++++ b/src/click/shell_completion.py +@@ -344,7 +344,7 @@ + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: +- return f"{item.value},{item.type.lower()}" ++ return f"{item.type},{item.value}" + + + class ZshComplete(ShellComplete): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/canaries/original-bug.sh b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/openenv.json b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/pallets__click.fde47b4b.combine_module__2aky5qvj/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..06c3984dcd03dc982eeef753422ac424ec46a5c4 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "f0cc6f61f174ab8c42f41731a38126c764e15c7ec197e5cc4950c2b5ed710f35", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "f354543dd1bec9aa52768110ab02bc691294f1d5a26d9a6a7ad66f851edb7ef3", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "aaef475adb67d743411dacc13ba34eaf984ac810db3c68d096985917e98e72bd", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "1e85ab11e5af025e8c5276de6de43c67aaa350de", + "source_completion_sha256": "5be3671b004a519e2611d2e00b26fec81d0d2c00561420085a7d727c6e1b13d2", + "source_index_sha256": "e3ea2fb9bd6c335cdb937a3a8cd4fe62a1ee4e9a65ba1e0deeeb395c0103fde1", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0e9dd0f103e9c77fa114629c5c37159c82f71a96f411e2153e59ee8367ab6669", + "is_fork": true, + "learner_path": "tasks/aa06df2000e7783baa7fb8aa/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/1e85ab11e5af025e8c5276de6de43c67aaa350de/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "fdbf70d0bdba36d60a82de7790987e84f5bd2b791cac941f976550c8b318c9df", + "provenance_path": "tasks/aa06df2000e7783baa7fb8aa/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "1e85ab11e5af025e8c5276de6de43c67aaa350de", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "38a3d0002f84dc27dd67f41dac51bf0536c0d32a", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "task_sha256": "78199609787249bc415bc10e8be41b98fe5c9251b877294f2ee05bd7aa3a5c04", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e83996d6a592b052a4415e56651c3e02b2261dba --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/instruction.md @@ -0,0 +1,28 @@ +Headers comparison and comma header parsing broken + +#### Description + +Headers comparison is returning incorrect results and comma-separated header parsing is not working properly. When comparing two identical Headers objects, they are incorrectly reported as not equal. Additionally, the `get_comma_header` function is not extracting header values correctly. + +#### Steps/Code to Reproduce + +```python +from h11._headers import Headers, get_comma_header + +# Headers comparison issue +headers1 = Headers([(b'content-type', b'Content-Type', b'text/html')]) +headers2 = Headers([(b'content-type', b'Content-Type', b'text/html')]) + +print("Headers equal:", headers1 == headers2) # Should be True, but returns False + +# Comma header parsing issue +headers = Headers([(b'connection', b'Connection', b'keep-alive, close')]) +result = get_comma_header(headers, b'connection') +print("Parsed values:", result) # Should return [b'keep-alive', b'close'], but returns [] +``` + +The first issue shows that identical Headers objects are not comparing as equal when they should be. The second issue demonstrates that `get_comma_header` is not properly extracting comma-separated values from headers. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8b04ab3d13fc00d22ee0514f06dfb70250cfb92a --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies" + ], + "PASS_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "38a3d0002f84dc27dd67f41dac51bf0536c0d32a", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "1e85ab11e5af025e8c5276de6de43c67aaa350de" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_events.py", + "h11/tests/test_headers.py", + "h11/tests/test_helpers.py", + "h11/tests/test_io.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": [ + "h11/_headers.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 987843, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0e9dd0f103e9c77fa114629c5c37159c82f71a96f411e2153e59ee8367ab6669", + "is_fork": true, + "learner_path": "tasks/aa06df2000e7783baa7fb8aa/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/1e85ab11e5af025e8c5276de6de43c67aaa350de/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "fdbf70d0bdba36d60a82de7790987e84f5bd2b791cac941f976550c8b318c9df", + "provenance_path": "tasks/aa06df2000e7783baa7fb8aa/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "1e85ab11e5af025e8c5276de6de43c67aaa350de", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "38a3d0002f84dc27dd67f41dac51bf0536c0d32a", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "task_sha256": "78199609787249bc415bc10e8be41b98fe5c9251b877294f2ee05bd7aa3a5c04", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..0b6234c339bee47fce9eb2e9a36a0ff219f76199 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "f0cc6f61f174ab8c42f41731a38126c764e15c7ec197e5cc4950c2b5ed710f35", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/1e85ab11e5af025e8c5276de6de43c67aaa350de/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "5be3671b004a519e2611d2e00b26fec81d0d2c00561420085a7d727c6e1b13d2", + "source_index_sha256": "e3ea2fb9bd6c335cdb937a3a8cd4fe62a1ee4e9a65ba1e0deeeb395c0103fde1", + "source_proof_sha256": "be7a61e78b7e706458e591dbb91a5be5422008aa869fad9865f83ecaae90cdac", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0e9dd0f103e9c77fa114629c5c37159c82f71a96f411e2153e59ee8367ab6669", + "is_fork": true, + "learner_path": "tasks/aa06df2000e7783baa7fb8aa/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/1e85ab11e5af025e8c5276de6de43c67aaa350de/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "fdbf70d0bdba36d60a82de7790987e84f5bd2b791cac941f976550c8b318c9df", + "provenance_path": "tasks/aa06df2000e7783baa7fb8aa/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "1e85ab11e5af025e8c5276de6de43c67aaa350de", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "38a3d0002f84dc27dd67f41dac51bf0536c0d32a", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1p8am6k1", + "task_sha256": "78199609787249bc415bc10e8be41b98fe5c9251b877294f2ee05bd7aa3a5c04", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..180efeb1697211e8077233e3d589528e9933eb5c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/provided-gold.diff @@ -0,0 +1,74 @@ +diff --git a/h11/_headers.py b/h11/_headers.py +index 09f24f9b06897f4577841051ee04ada318e02086..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -100,13 +100,13 @@ + __slots__ = "_full_items" + + def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: +- self._full_items = full_items.copy()[::-1] ++ self._full_items = full_items + + def __bool__(self) -> bool: + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: +- return list(self) != list(other) ++ return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) +@@ -203,13 +203,48 @@ + + + def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: ++ # Should only be used for headers whose value is a list of ++ # comma-separated, case-insensitive values. ++ # ++ # The header name `name` is expected to be lower-case bytes. ++ # ++ # Connection: meets these criteria (including cast insensitivity). ++ # ++ # Content-Length: technically is just a single value (1*DIGIT), but the ++ # standard makes reference to implementations that do multiple values, and ++ # using this doesn't hurt. Ditto, case insensitivity doesn't things either ++ # way. ++ # ++ # Transfer-Encoding: is more complex (allows for quoted strings), so ++ # splitting on , is actually wrong. For example, this is legal: ++ # ++ # Transfer-Encoding: foo; options="1,2", chunked ++ # ++ # and should be parsed as ++ # ++ # foo; options="1,2" ++ # chunked ++ # ++ # but this naive function will parse it as ++ # ++ # foo; options="1 ++ # 2" ++ # chunked ++ # ++ # However, this is okay because the only thing we are going to do with ++ # any Transfer-Encoding is reject ones that aren't just "chunked", so ++ # both of these will be treated the same anyway. ++ # ++ # Expect: the only legal value is the literal string ++ # "100-continue". Splitting on commas is harmless. Case insensitive. ++ # + out: List[bytes] = [] + for _, found_name, found_raw_value in headers._full_items: +- if found_name != name: +- found_raw_value = found_raw_value.upper() +- for found_split_value in found_raw_value.split(b";"): +- found_split_value = found_split_value.lstrip() +- if not found_split_value: ++ if found_name == name: ++ found_raw_value = found_raw_value.lower() ++ for found_split_value in found_raw_value.split(b","): ++ found_split_value = found_split_value.strip() ++ if found_split_value: + out.append(found_split_value) + return out + diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..00a4d26c23432a98e57047dd5fe0d3be1caa6777 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/solution/solve.sh @@ -0,0 +1,80 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_headers.py b/h11/_headers.py +index 09f24f9b06897f4577841051ee04ada318e02086..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -100,13 +100,13 @@ + __slots__ = "_full_items" + + def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: +- self._full_items = full_items.copy()[::-1] ++ self._full_items = full_items + + def __bool__(self) -> bool: + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: +- return list(self) != list(other) ++ return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) +@@ -203,13 +203,48 @@ + + + def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: ++ # Should only be used for headers whose value is a list of ++ # comma-separated, case-insensitive values. ++ # ++ # The header name `name` is expected to be lower-case bytes. ++ # ++ # Connection: meets these criteria (including cast insensitivity). ++ # ++ # Content-Length: technically is just a single value (1*DIGIT), but the ++ # standard makes reference to implementations that do multiple values, and ++ # using this doesn't hurt. Ditto, case insensitivity doesn't things either ++ # way. ++ # ++ # Transfer-Encoding: is more complex (allows for quoted strings), so ++ # splitting on , is actually wrong. For example, this is legal: ++ # ++ # Transfer-Encoding: foo; options="1,2", chunked ++ # ++ # and should be parsed as ++ # ++ # foo; options="1,2" ++ # chunked ++ # ++ # but this naive function will parse it as ++ # ++ # foo; options="1 ++ # 2" ++ # chunked ++ # ++ # However, this is okay because the only thing we are going to do with ++ # any Transfer-Encoding is reject ones that aren't just "chunked", so ++ # both of these will be treated the same anyway. ++ # ++ # Expect: the only legal value is the literal string ++ # "100-continue". Splitting on commas is harmless. Case insensitive. ++ # + out: List[bytes] = [] + for _, found_name, found_raw_value in headers._full_items: +- if found_name != name: +- found_raw_value = found_raw_value.upper() +- for found_split_value in found_raw_value.split(b";"): +- found_split_value = found_split_value.lstrip() +- if not found_split_value: ++ if found_name == name: ++ found_raw_value = found_raw_value.lower() ++ for found_split_value in found_raw_value.split(b","): ++ found_split_value = found_split_value.strip() ++ if found_split_value: + out.append(found_split_value) + return out + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..7fe0a71f9efbeead8e16739d1d4865c352df263f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies" + ], + "pass-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..5e029e555ef98dfc5689d7c1513b58e4144f44d8 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/canaries/first-hunk-only.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_headers.py b/h11/_headers.py +index 09f24f9b06897f4577841051ee04ada318e02086..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -100,13 +100,13 @@ + __slots__ = "_full_items" + + def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: +- self._full_items = full_items.copy()[::-1] ++ self._full_items = full_items + + def __bool__(self) -> bool: + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: +- return list(self) != list(other) ++ return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1p8am6k1/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..eeb307ba9f6b210901b3a13ace883c7e782f3284 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "7438125cc600f651a5378c33675b9dba786c485c1966ae27d8f3b1ac05a6dbf5", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "83c7189b2b65809d162f70071e244acedf313f971f374f5e4e1259185b9dfd1d", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "238d8181441f9065cfc15542b7f1e13541e8c40a668ced664f82fc42099e2da5", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "7f314dcf87276ba12088ec569a38f5b03fdf75c2", + "source_completion_sha256": "1c85afd43ffee4f6e7e85066310eba2693e6beae1f10bbac97323bef764ce5b5", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0ce7c28d6d1ea9df9f898becf9ede2fb5ce3e504f0e3287529b662cff1e9fd73", + "is_fork": true, + "learner_path": "tasks/b5bb1f863bf239707599c052/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/7f314dcf87276ba12088ec569a38f5b03fdf75c2/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "f85c6facd4e25edef79c828fbc0f9a851cd587b97ec674fc2ab27e5f87681950", + "provenance_path": "tasks/b5bb1f863bf239707599c052/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "7f314dcf87276ba12088ec569a38f5b03fdf75c2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "0e5e205049c536d5fbe1c1d201e82bcab7d564e7", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "task_sha256": "546850b02f3cfda7adf64878fb41858d2b21c5eb00976bb839127952de0c289c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdfb56f58040213ceff91942e5f011100acb513d --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/instruction.md @@ -0,0 +1,31 @@ +Headers equality comparison returns inverted result + +#### Description + +When comparing Headers objects for equality, the comparison returns the opposite of what it should. Two identical Headers objects are reported as not equal, and different Headers objects are reported as equal. + +#### Steps/Code to Reproduce + +```python +from h11 import Headers + +# Create two identical headers +headers1 = Headers([('content-type', 'text/html'), ('content-length', '100')]) +headers2 = Headers([('content-type', 'text/html'), ('content-length', '100')]) + +# This should be True but returns False +print(headers1 == headers2) # False + +# Create different headers +headers3 = Headers([('content-type', 'application/json')]) +headers4 = Headers([('content-length', '200')]) + +# This should be False but returns True +print(headers3 == headers4) # True +``` + +The equality comparison is behaving in reverse - identical headers are considered unequal and different headers are considered equal. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..ec65cf41e5703fc31d8841e85186854d108d9969 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies" + ], + "PASS_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "0e5e205049c536d5fbe1c1d201e82bcab7d564e7", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "7f314dcf87276ba12088ec569a38f5b03fdf75c2" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_against_stdlib_http.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_connection.py", + "h11/tests/test_events.py", + "h11/tests/test_headers.py", + "h11/tests/test_helpers.py", + "h11/tests/test_io.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": [ + "h11/_headers.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 993973, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0ce7c28d6d1ea9df9f898becf9ede2fb5ce3e504f0e3287529b662cff1e9fd73", + "is_fork": true, + "learner_path": "tasks/b5bb1f863bf239707599c052/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/7f314dcf87276ba12088ec569a38f5b03fdf75c2/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "f85c6facd4e25edef79c828fbc0f9a851cd587b97ec674fc2ab27e5f87681950", + "provenance_path": "tasks/b5bb1f863bf239707599c052/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "7f314dcf87276ba12088ec569a38f5b03fdf75c2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "0e5e205049c536d5fbe1c1d201e82bcab7d564e7", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "task_sha256": "546850b02f3cfda7adf64878fb41858d2b21c5eb00976bb839127952de0c289c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..2ed2d37b20fe811af429b4036b2d9cb427658eec --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "7438125cc600f651a5378c33675b9dba786c485c1966ae27d8f3b1ac05a6dbf5", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/7f314dcf87276ba12088ec569a38f5b03fdf75c2/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "1c85afd43ffee4f6e7e85066310eba2693e6beae1f10bbac97323bef764ce5b5", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "81745960249488ac8e46b7023928c99d60e31cf5727b9107195d7739777b74a9", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0ce7c28d6d1ea9df9f898becf9ede2fb5ce3e504f0e3287529b662cff1e9fd73", + "is_fork": true, + "learner_path": "tasks/b5bb1f863bf239707599c052/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/7f314dcf87276ba12088ec569a38f5b03fdf75c2/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "f85c6facd4e25edef79c828fbc0f9a851cd587b97ec674fc2ab27e5f87681950", + "provenance_path": "tasks/b5bb1f863bf239707599c052/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "7f314dcf87276ba12088ec569a38f5b03fdf75c2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "0e5e205049c536d5fbe1c1d201e82bcab7d564e7", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__1uccq29y", + "task_sha256": "546850b02f3cfda7adf64878fb41858d2b21c5eb00976bb839127952de0c289c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..7b37af0f431985ea06293102785b62bddf8872f4 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/provided-gold.diff @@ -0,0 +1,27 @@ +diff --git a/h11/_headers.py b/h11/_headers.py +index 2c35df706b6a26839bcfafcc36ab1bae2c1e951a..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -106,7 +106,7 @@ + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: +- return list(self) != list(other) ++ return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) +@@ -269,7 +269,10 @@ + + + def has_expect_100_continue(request: "Request") -> bool: +- if request.http_version <= b"1.1": +- return True ++ # https://tools.ietf.org/html/rfc7231#section-5.1.1 ++ # "A server that receives a 100-continue expectation in an HTTP/1.0 request ++ # MUST ignore that expectation." ++ if request.http_version < b"1.1": ++ return False + expect = get_comma_header(request.headers, b"expect") +- return b"100-continue" not in expect ++ return b"100-continue" in expect diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6171eb869b71304acbc6d16abd67eb87f5f95dae --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/solution/solve.sh @@ -0,0 +1,33 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_headers.py b/h11/_headers.py +index 2c35df706b6a26839bcfafcc36ab1bae2c1e951a..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -106,7 +106,7 @@ + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: +- return list(self) != list(other) ++ return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) +@@ -269,7 +269,10 @@ + + + def has_expect_100_continue(request: "Request") -> bool: +- if request.http_version <= b"1.1": +- return True ++ # https://tools.ietf.org/html/rfc7231#section-5.1.1 ++ # "A server that receives a 100-continue expectation in an HTTP/1.0 request ++ # MUST ignore that expectation." ++ if request.http_version < b"1.1": ++ return False + expect = get_comma_header(request.headers, b"expect") +- return b"100-continue" not in expect ++ return b"100-continue" in expect +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..5e83c619ba65ac681cd88d97f944d63e95488e06 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies" + ], + "pass-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e1cf14f2572ef2686df059305a858f265603829 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_headers.py b/h11/_headers.py +index 2c35df706b6a26839bcfafcc36ab1bae2c1e951a..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -106,7 +106,7 @@ + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: +- return list(self) != list(other) ++ return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__1uccq29y/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..4aad45d6a11ab9e55e156453607d9787498494b0 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "ae469bb74119a58c669302974dae5847559f5309093a8af5897df8cf2b6cc8c2", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "bec30705bcb503c2ee5e17be90bc6a70900c65cf1b2c4b14b28919c3b925b9b5", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "42ac14be9a08997ae404f9caaef9a14057c9d8608891a7ea8221a6e492d25824", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "2a0b30f45aa1495c94686463849c270a6b2687a4", + "source_completion_sha256": "45cd31a944fe5a1ccb1b78a8eddd085f9456a21aaa98db4524d79d9343b202c8", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "ec4718aa7ed084a0934fea308e1fdadb65eebaa550573001e8c58442ca64e915", + "is_fork": true, + "learner_path": "tasks/3d7875605fcf7b3343507ff5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/2a0b30f45aa1495c94686463849c270a6b2687a4/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "b0a86d6f582d3d2958a9af102a941360f76881f02f2598c99844d03307774219", + "provenance_path": "tasks/3d7875605fcf7b3343507ff5/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2a0b30f45aa1495c94686463849c270a6b2687a4", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5307dde800e53f123b445bc779f1ad683838c525", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "task_sha256": "8e45d55087c07abf630abfcea12f3d1e53d52d71e066698df41530a25ccb5007", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8ee4df4313eb9fc816e019bef608782cd930b49e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/instruction.md @@ -0,0 +1,45 @@ +Connection state machine broken after recent changes + +#### Description + +The HTTP connection state machine is not working correctly. Basic HTTP request/response cycles are failing with various errors including `AttributeError: 'tuple' object has no attribute 'add'` and incorrect state transitions. + +#### Steps/Code to Reproduce + +```python +from h11 import Connection, Request, Response, EndOfMessage, CLIENT, SERVER + +# Simple client-server interaction fails +c = Connection(SERVER) +c.receive_data(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n') +request = c.next_event() +print(f"Request: {request}") + +c.send(Response(status_code=200, headers=[])) +c.send(EndOfMessage()) +print(f"Server state: {c.our_state}") +``` + +This should work for basic HTTP handling but currently raises errors. + +Also connection reuse is broken: + +```python +from h11 import Connection, Request, Response, EndOfMessage, CLIENT, SERVER + +c = Connection(CLIENT) +c.send(Request(method='GET', target='/', headers=[('Host', 'example.com')])) +c.send(EndOfMessage()) + +# Simulate server response +c.receive_data(b'HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n') +response = c.next_event() +c.next_event() # EndOfMessage + +# Try to reuse connection +c.start_next_cycle() # This should work but fails +``` + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..d1731527d3f9a3c871125a5486b96205ea655131 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "5307dde800e53f123b445bc779f1ad683838c525", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "2a0b30f45aa1495c94686463849c270a6b2687a4" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_io.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_state.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": [ + "h11/_state.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1008218, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "ec4718aa7ed084a0934fea308e1fdadb65eebaa550573001e8c58442ca64e915", + "is_fork": true, + "learner_path": "tasks/3d7875605fcf7b3343507ff5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/2a0b30f45aa1495c94686463849c270a6b2687a4/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "b0a86d6f582d3d2958a9af102a941360f76881f02f2598c99844d03307774219", + "provenance_path": "tasks/3d7875605fcf7b3343507ff5/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2a0b30f45aa1495c94686463849c270a6b2687a4", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5307dde800e53f123b445bc779f1ad683838c525", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "task_sha256": "8e45d55087c07abf630abfcea12f3d1e53d52d71e066698df41530a25ccb5007", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ac0f8094a45bebb9bfdf8163c965aa052fb6a14e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "ae469bb74119a58c669302974dae5847559f5309093a8af5897df8cf2b6cc8c2", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/2a0b30f45aa1495c94686463849c270a6b2687a4/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "45cd31a944fe5a1ccb1b78a8eddd085f9456a21aaa98db4524d79d9343b202c8", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "ebb74d076eeb35ad74b40bcc972a4641f0e2ab39044f879b93d58eb063182331", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "ec4718aa7ed084a0934fea308e1fdadb65eebaa550573001e8c58442ca64e915", + "is_fork": true, + "learner_path": "tasks/3d7875605fcf7b3343507ff5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/2a0b30f45aa1495c94686463849c270a6b2687a4/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "b0a86d6f582d3d2958a9af102a941360f76881f02f2598c99844d03307774219", + "provenance_path": "tasks/3d7875605fcf7b3343507ff5/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2a0b30f45aa1495c94686463849c270a6b2687a4", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5307dde800e53f123b445bc779f1ad683838c525", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__2hozrie3", + "task_sha256": "8e45d55087c07abf630abfcea12f3d1e53d52d71e066698df41530a25ccb5007", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..4f2e9ce4e369a9aeb44b8a9b9bd54c891278cbac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/provided-gold.diff @@ -0,0 +1,49 @@ +diff --git a/h11/_state.py b/h11/_state.py +index 93379636147c45227b4d8eaf5830239dcd44e9a0..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 100644 +--- a/h11/_state.py ++++ b/h11/_state.py +@@ -281,19 +281,19 @@ + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER +- if server_switch_event in self.pending_switch_proposals: ++ if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( +- "Received server _SWITCH_UPGRADE event with a pending proposal" ++ "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) +- if server_switch_event is None and event_type is Response: +- self.pending_switch_proposals = list() ++ if server_switch_event is None and _event_type is Response: ++ self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) +- # Special case: the server state does get to see Response ++ # Special case: the server state does get to see Request + # events. +- if _event_type is Response: +- assert role is SERVER +- self._fire_event_triggered_transitions(CLIENT, (Request, SERVER)) ++ if _event_type is Request: ++ assert role is CLIENT ++ self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( +@@ -354,10 +354,12 @@ + return + + def start_next_cycle(self) -> None: +- if self.states != {CLIENT: IDLE, SERVER: IDLE}: ++ if self.states != {CLIENT: DONE, SERVER: DONE}: + raise LocalProtocolError( + f"not in a reusable state. self.states={self.states}" + ) +- assert not self.keep_alive +- assert self.pending_switch_proposals +- self.states = {CLIENT: DONE, SERVER: IDLE} ++ # Can't reach DONE/DONE with any of these active, but still, let's be ++ # sure. ++ assert self.keep_alive ++ assert not self.pending_switch_proposals ++ self.states = {CLIENT: IDLE, SERVER: IDLE} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c74a1d85b6e29eb98adc89d65c130c6b5f3e4f56 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/solution/solve.sh @@ -0,0 +1,55 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_state.py b/h11/_state.py +index 93379636147c45227b4d8eaf5830239dcd44e9a0..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 100644 +--- a/h11/_state.py ++++ b/h11/_state.py +@@ -281,19 +281,19 @@ + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER +- if server_switch_event in self.pending_switch_proposals: ++ if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( +- "Received server _SWITCH_UPGRADE event with a pending proposal" ++ "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) +- if server_switch_event is None and event_type is Response: +- self.pending_switch_proposals = list() ++ if server_switch_event is None and _event_type is Response: ++ self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) +- # Special case: the server state does get to see Response ++ # Special case: the server state does get to see Request + # events. +- if _event_type is Response: +- assert role is SERVER +- self._fire_event_triggered_transitions(CLIENT, (Request, SERVER)) ++ if _event_type is Request: ++ assert role is CLIENT ++ self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( +@@ -354,10 +354,12 @@ + return + + def start_next_cycle(self) -> None: +- if self.states != {CLIENT: IDLE, SERVER: IDLE}: ++ if self.states != {CLIENT: DONE, SERVER: DONE}: + raise LocalProtocolError( + f"not in a reusable state. self.states={self.states}" + ) +- assert not self.keep_alive +- assert self.pending_switch_proposals +- self.states = {CLIENT: DONE, SERVER: IDLE} ++ # Can't reach DONE/DONE with any of these active, but still, let's be ++ # sure. ++ assert self.keep_alive ++ assert not self.pending_switch_proposals ++ self.states = {CLIENT: IDLE, SERVER: IDLE} +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..4f443f5a8f65b911e94595e768d13e10894f8ef8 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8df362c09b3bf5e52e1bb2823a3e78b7fc4cfdc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/canaries/first-hunk-only.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_state.py b/h11/_state.py +index 93379636147c45227b4d8eaf5830239dcd44e9a0..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 100644 +--- a/h11/_state.py ++++ b/h11/_state.py +@@ -281,19 +281,19 @@ + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER +- if server_switch_event in self.pending_switch_proposals: ++ if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( +- "Received server _SWITCH_UPGRADE event with a pending proposal" ++ "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) +- if server_switch_event is None and event_type is Response: +- self.pending_switch_proposals = list() ++ if server_switch_event is None and _event_type is Response: ++ self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) +- # Special case: the server state does get to see Response ++ # Special case: the server state does get to see Request + # events. +- if _event_type is Response: +- assert role is SERVER +- self._fire_event_triggered_transitions(CLIENT, (Request, SERVER)) ++ if _event_type is Request: ++ assert role is CLIENT ++ self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__2hozrie3/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..5f09adbe7e1e950f58ce9b4ebd0593d7f59a944c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "3a5f39f80630e162dccff42b02d34fde8e55b1d5c785f60617a0009f6c2bebe2", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "154ee7f0f508595a12008726fecc363692f9c90d08ffae02713f992c433a9097", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "e4dddc7898d21411d975c322c2ae0ef7234ed2d7901706ae27b8f3b818de7df1", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2", + "source_completion_sha256": "57bdc38f1fbf1c8a8fc32030f52761524bc545a89f618c7853d07ab65da4b293", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "fbef1d6e4ae87e6618b9949eb1e7d03247dc75f165e7276e04dc7f89e694f5e3", + "is_fork": true, + "learner_path": "tasks/fdeddb1168421bdaf10f12aa/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "ed582dfd29e2570d5be1ff745bc8becaade7548514e84c6a7bc07f30bf2879fd", + "provenance_path": "tasks/fdeddb1168421bdaf10f12aa/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f77fe5a0344e06f1fe9ecd5bd3fa30351d9c5a2a", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "task_sha256": "770eff7764de39b42d0eb7aaf0a0c8e4bc95744bcf387887fb272d2361746cd8", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5fd9c44f3a9acbf8ebe3bd149f2303b279f8b3e0 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/instruction.md @@ -0,0 +1,25 @@ +LocalProtocolError re-raising behavior changed unexpectedly + +Description + +When catching a LocalProtocolError and calling `_reraise_as_remote_protocol_error()`, the method now raises a RuntimeError instead of properly re-raising as a RemoteProtocolError. + +Steps/Code to Reproduce + +```python +from h11._util import LocalProtocolError + +try: + raise LocalProtocolError("test error") +except LocalProtocolError as e: + e._reraise_as_remote_protocol_error() +``` + +Expected: Should raise RemoteProtocolError +Actual: Raises RuntimeError("Re-raised as RuntimeError") + +This affects various parts of the h11 library where protocol errors need to be converted from local to remote errors during connection handling. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9ad60d542d19ec356f629aebb69c7a9fc14df642 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError" + ], + "PASS_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "f77fe5a0344e06f1fe9ecd5bd3fa30351d9c5a2a", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_against_stdlib_http.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_io.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_connection.py", + "h11/tests/test_headers.py", + "h11/tests/test_util.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": [ + "h11/_util.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1011022, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "fbef1d6e4ae87e6618b9949eb1e7d03247dc75f165e7276e04dc7f89e694f5e3", + "is_fork": true, + "learner_path": "tasks/fdeddb1168421bdaf10f12aa/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "ed582dfd29e2570d5be1ff745bc8becaade7548514e84c6a7bc07f30bf2879fd", + "provenance_path": "tasks/fdeddb1168421bdaf10f12aa/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f77fe5a0344e06f1fe9ecd5bd3fa30351d9c5a2a", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "task_sha256": "770eff7764de39b42d0eb7aaf0a0c8e4bc95744bcf387887fb272d2361746cd8", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..2fc8b80d5df1ec72c76748fe62e44fd7493f00b8 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "3a5f39f80630e162dccff42b02d34fde8e55b1d5c785f60617a0009f6c2bebe2", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "57bdc38f1fbf1c8a8fc32030f52761524bc545a89f618c7853d07ab65da4b293", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "35a52b9244d2fa1c53c99c8167bc414cc125be7d23086048c346706e70b3aed8", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "fbef1d6e4ae87e6618b9949eb1e7d03247dc75f165e7276e04dc7f89e694f5e3", + "is_fork": true, + "learner_path": "tasks/fdeddb1168421bdaf10f12aa/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "ed582dfd29e2570d5be1ff745bc8becaade7548514e84c6a7bc07f30bf2879fd", + "provenance_path": "tasks/fdeddb1168421bdaf10f12aa/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "85ce3c4efe4e3c46f5c0e28b3a2eb91bef8bdbd2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f77fe5a0344e06f1fe9ecd5bd3fa30351d9c5a2a", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__3ukf7amt", + "task_sha256": "770eff7764de39b42d0eb7aaf0a0c8e4bc95744bcf387887fb272d2361746cd8", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..fad2872855f664c56400ec899d523780f41ba79f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/provided-gold.diff @@ -0,0 +1,42 @@ +diff --git a/h11/_util.py b/h11/_util.py +index de60e8bc8c7ebaaa6a12c1264f98aee5ee7eaf48..6718445290770e028ea2f1f662026c9a0b0991db 100644 +--- a/h11/_util.py ++++ b/h11/_util.py +@@ -40,9 +40,9 @@ + + def __init__(self, msg: str, error_status_hint: int = 400) -> None: + if type(self) is ProtocolError: +- raise ValueError("tried to directly instantiate ProtocolError") ++ raise TypeError("tried to directly instantiate ProtocolError") + Exception.__init__(self, msg) +- self.error_status_hint = 404 ++ self.error_status_hint = error_status_hint + + + # Strategy: there are a number of public APIs where a LocalProtocolError can +@@ -58,9 +58,23 @@ + # remote errors. + class LocalProtocolError(ProtocolError): + def _reraise_as_remote_protocol_error(self) -> NoReturn: ++ # After catching a LocalProtocolError, use this method to re-raise it ++ # as a RemoteProtocolError. This method must be called from inside an ++ # except: block. ++ # ++ # An easy way to get an equivalent RemoteProtocolError is just to ++ # modify 'self' in place. + self.__class__ = RemoteProtocolError # type: ignore +- # Intentionally modified the raise statement +- raise RuntimeError("Re-raised as RuntimeError") ++ # But the re-raising is somewhat non-trivial -- you might think that ++ # now that we've modified the in-flight exception object, that just ++ # doing 'raise' to re-raise it would be enough. But it turns out that ++ # this doesn't work, because Python tracks the exception type ++ # (exc_info[0]) separately from the exception object (exc_info[1]), ++ # and we only modified the latter. So we really do need to re-raise ++ # the new type explicitly. ++ # On py3, the traceback is part of the exception object, so our ++ # in-place modification preserved it and we can just re-raise: ++ raise self + + + class RemoteProtocolError(ProtocolError): diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7c049f347977a9d845675e06d6d565975f215d45 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/solution/solve.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_util.py b/h11/_util.py +index de60e8bc8c7ebaaa6a12c1264f98aee5ee7eaf48..6718445290770e028ea2f1f662026c9a0b0991db 100644 +--- a/h11/_util.py ++++ b/h11/_util.py +@@ -40,9 +40,9 @@ + + def __init__(self, msg: str, error_status_hint: int = 400) -> None: + if type(self) is ProtocolError: +- raise ValueError("tried to directly instantiate ProtocolError") ++ raise TypeError("tried to directly instantiate ProtocolError") + Exception.__init__(self, msg) +- self.error_status_hint = 404 ++ self.error_status_hint = error_status_hint + + + # Strategy: there are a number of public APIs where a LocalProtocolError can +@@ -58,9 +58,23 @@ + # remote errors. + class LocalProtocolError(ProtocolError): + def _reraise_as_remote_protocol_error(self) -> NoReturn: ++ # After catching a LocalProtocolError, use this method to re-raise it ++ # as a RemoteProtocolError. This method must be called from inside an ++ # except: block. ++ # ++ # An easy way to get an equivalent RemoteProtocolError is just to ++ # modify 'self' in place. + self.__class__ = RemoteProtocolError # type: ignore +- # Intentionally modified the raise statement +- raise RuntimeError("Re-raised as RuntimeError") ++ # But the re-raising is somewhat non-trivial -- you might think that ++ # now that we've modified the in-flight exception object, that just ++ # doing 'raise' to re-raise it would be enough. But it turns out that ++ # this doesn't work, because Python tracks the exception type ++ # (exc_info[0]) separately from the exception object (exc_info[1]), ++ # and we only modified the latter. So we really do need to re-raise ++ # the new type explicitly. ++ # On py3, the traceback is part of the exception object, so our ++ # in-place modification preserved it and we can just re-raise: ++ raise self + + + class RemoteProtocolError(ProtocolError): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..386016c7abfdcc27fe415f9c259da0976a235015 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError" + ], + "pass-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..04d1ecee8d574ed39d0f2f49dd8e134123f12642 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/canaries/first-hunk-only.sh @@ -0,0 +1,22 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_util.py b/h11/_util.py +index de60e8bc8c7ebaaa6a12c1264f98aee5ee7eaf48..6718445290770e028ea2f1f662026c9a0b0991db 100644 +--- a/h11/_util.py ++++ b/h11/_util.py +@@ -40,9 +40,9 @@ + + def __init__(self, msg: str, error_status_hint: int = 400) -> None: + if type(self) is ProtocolError: +- raise ValueError("tried to directly instantiate ProtocolError") ++ raise TypeError("tried to directly instantiate ProtocolError") + Exception.__init__(self, msg) +- self.error_status_hint = 404 ++ self.error_status_hint = error_status_hint + + + # Strategy: there are a number of public APIs where a LocalProtocolError can +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__3ukf7amt/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..10c59cd4b5043bcbf96bdfcfdc3a3bfab2417d25 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "77c05e4b000c7bdd0b60890ea8f0ce2ea8b8e683fd97237e4dad8022b4ba50b8", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "24e43abfa2c6babaaf838ee5c5acf5e1667b7ba6fe527abb1234c2b8aecb5e96", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "763d1a13e8a2aed644847ae079fc86da5693f046107251761280ecc3cb1b992a", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "a3edcf4f8e87983cd1507ed6532b765c68a9bc8e", + "source_completion_sha256": "636b68e3e9453ed0c012d97d4486c1f2323911130d0658df814a8f67d69462bf", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "f84b178c03e8e99db90450aaee7012aa416193be2b2bb0bfd269a3533da1883b", + "is_fork": true, + "learner_path": "tasks/65b532e6cb1c18d929b763d8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a3edcf4f8e87983cd1507ed6532b765c68a9bc8e/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "740ddb257db33405db5b669dbf3f087fc5d31316aab8fd703298db4fe6cfc95d", + "provenance_path": "tasks/65b532e6cb1c18d929b763d8/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a3edcf4f8e87983cd1507ed6532b765c68a9bc8e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d076244e7da51d026f93d07d7e45d933cc6c1604", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "task_sha256": "eee7ea8ada8bde501ff59367638d6baa3b34da1c32146888a7c22a923183083e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..62c0c7a0df74df1f9e5e8094aeb92e185cc3c491 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/instruction.md @@ -0,0 +1,26 @@ +Headers.__len__ returns incorrect value when empty + +#### Description + +When creating an empty Headers object, `len(headers)` returns -1 instead of 0, and `bool(headers)` evaluates to True for headers with only one item. + +#### Steps/Code to Reproduce + +```python +from h11 import Headers + +# Empty headers should have length 0, not -1 +empty_headers = Headers([]) +print(f"len(empty_headers): {len(empty_headers)}") # prints -1, should be 0 + +# Single header should be truthy, but currently isn't +single_header = Headers([("content-type", "text/html")]) +print(f"bool(single_header): {bool(single_header)}") # prints False, should be True +print(f"len(single_header): {len(single_header)}") # prints 0, should be 1 +``` + +The issue affects basic operations on Headers objects and breaks expected behavior for empty and single-item collections. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..a1a0ca0f5b9a9115d08b0040aa67d9c00c947aa5 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "d076244e7da51d026f93d07d7e45d933cc6c1604", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "a3edcf4f8e87983cd1507ed6532b765c68a9bc8e" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_events.py", + "h11/tests/test_headers.py", + "h11/tests/test_helpers.py", + "h11/tests/test_io.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": [ + "h11/_headers.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 987525, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "f84b178c03e8e99db90450aaee7012aa416193be2b2bb0bfd269a3533da1883b", + "is_fork": true, + "learner_path": "tasks/65b532e6cb1c18d929b763d8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a3edcf4f8e87983cd1507ed6532b765c68a9bc8e/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "740ddb257db33405db5b669dbf3f087fc5d31316aab8fd703298db4fe6cfc95d", + "provenance_path": "tasks/65b532e6cb1c18d929b763d8/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a3edcf4f8e87983cd1507ed6532b765c68a9bc8e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d076244e7da51d026f93d07d7e45d933cc6c1604", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "task_sha256": "eee7ea8ada8bde501ff59367638d6baa3b34da1c32146888a7c22a923183083e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..1b3336c59c7844d7983462374217cfebd7241ff8 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "77c05e4b000c7bdd0b60890ea8f0ce2ea8b8e683fd97237e4dad8022b4ba50b8", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a3edcf4f8e87983cd1507ed6532b765c68a9bc8e/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "636b68e3e9453ed0c012d97d4486c1f2323911130d0658df814a8f67d69462bf", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "36fceb7b733c200af657dcf7d8e59087d8f9931c6905472cb693a9daf35c3992", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "f84b178c03e8e99db90450aaee7012aa416193be2b2bb0bfd269a3533da1883b", + "is_fork": true, + "learner_path": "tasks/65b532e6cb1c18d929b763d8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a3edcf4f8e87983cd1507ed6532b765c68a9bc8e/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "740ddb257db33405db5b669dbf3f087fc5d31316aab8fd703298db4fe6cfc95d", + "provenance_path": "tasks/65b532e6cb1c18d929b763d8/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a3edcf4f8e87983cd1507ed6532b765c68a9bc8e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d076244e7da51d026f93d07d7e45d933cc6c1604", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4fir9h4i", + "task_sha256": "eee7ea8ada8bde501ff59367638d6baa3b34da1c32146888a7c22a923183083e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a9b52e0e9581a7069e1d2f9116594a264fa55c52 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/provided-gold.diff @@ -0,0 +1,88 @@ +diff --git a/h11/_headers.py b/h11/_headers.py +index 2d203586ec3941fa50a1d05ca58a2ca3a2675ae1..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -103,13 +103,13 @@ + self._full_items = full_items + + def __bool__(self) -> bool: +- return len(self._full_items) > 1 ++ return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: +- return len(self._full_items) - 1 ++ return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) +@@ -203,13 +203,48 @@ + + + def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: ++ # Should only be used for headers whose value is a list of ++ # comma-separated, case-insensitive values. ++ # ++ # The header name `name` is expected to be lower-case bytes. ++ # ++ # Connection: meets these criteria (including cast insensitivity). ++ # ++ # Content-Length: technically is just a single value (1*DIGIT), but the ++ # standard makes reference to implementations that do multiple values, and ++ # using this doesn't hurt. Ditto, case insensitivity doesn't things either ++ # way. ++ # ++ # Transfer-Encoding: is more complex (allows for quoted strings), so ++ # splitting on , is actually wrong. For example, this is legal: ++ # ++ # Transfer-Encoding: foo; options="1,2", chunked ++ # ++ # and should be parsed as ++ # ++ # foo; options="1,2" ++ # chunked ++ # ++ # but this naive function will parse it as ++ # ++ # foo; options="1 ++ # 2" ++ # chunked ++ # ++ # However, this is okay because the only thing we are going to do with ++ # any Transfer-Encoding is reject ones that aren't just "chunked", so ++ # both of these will be treated the same anyway. ++ # ++ # Expect: the only legal value is the literal string ++ # "100-continue". Splitting on commas is harmless. Case insensitive. ++ # + out: List[bytes] = [] + for _, found_name, found_raw_value in headers._full_items: +- if found_name != name: +- found_raw_value = found_raw_value.upper() +- for found_split_value in found_raw_value.split(b";"): +- found_split_value = found_split_value.lstrip() +- if not found_split_value: ++ if found_name == name: ++ found_raw_value = found_raw_value.lower() ++ for found_split_value in found_raw_value.split(b","): ++ found_split_value = found_split_value.strip() ++ if found_split_value: + out.append(found_split_value) + return out + +@@ -234,7 +269,10 @@ + + + def has_expect_100_continue(request: "Request") -> bool: +- if request.http_version <= b"1.1": +- return True ++ # https://tools.ietf.org/html/rfc7231#section-5.1.1 ++ # "A server that receives a 100-continue expectation in an HTTP/1.0 request ++ # MUST ignore that expectation." ++ if request.http_version < b"1.1": ++ return False + expect = get_comma_header(request.headers, b"expect") +- return b"100-continue" not in expect ++ return b"100-continue" in expect diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..614b266caa6c3c472c0fde4aba4fd332b1dccab4 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/solution/solve.sh @@ -0,0 +1,94 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_headers.py b/h11/_headers.py +index 2d203586ec3941fa50a1d05ca58a2ca3a2675ae1..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -103,13 +103,13 @@ + self._full_items = full_items + + def __bool__(self) -> bool: +- return len(self._full_items) > 1 ++ return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: +- return len(self._full_items) - 1 ++ return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) +@@ -203,13 +203,48 @@ + + + def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: ++ # Should only be used for headers whose value is a list of ++ # comma-separated, case-insensitive values. ++ # ++ # The header name `name` is expected to be lower-case bytes. ++ # ++ # Connection: meets these criteria (including cast insensitivity). ++ # ++ # Content-Length: technically is just a single value (1*DIGIT), but the ++ # standard makes reference to implementations that do multiple values, and ++ # using this doesn't hurt. Ditto, case insensitivity doesn't things either ++ # way. ++ # ++ # Transfer-Encoding: is more complex (allows for quoted strings), so ++ # splitting on , is actually wrong. For example, this is legal: ++ # ++ # Transfer-Encoding: foo; options="1,2", chunked ++ # ++ # and should be parsed as ++ # ++ # foo; options="1,2" ++ # chunked ++ # ++ # but this naive function will parse it as ++ # ++ # foo; options="1 ++ # 2" ++ # chunked ++ # ++ # However, this is okay because the only thing we are going to do with ++ # any Transfer-Encoding is reject ones that aren't just "chunked", so ++ # both of these will be treated the same anyway. ++ # ++ # Expect: the only legal value is the literal string ++ # "100-continue". Splitting on commas is harmless. Case insensitive. ++ # + out: List[bytes] = [] + for _, found_name, found_raw_value in headers._full_items: +- if found_name != name: +- found_raw_value = found_raw_value.upper() +- for found_split_value in found_raw_value.split(b";"): +- found_split_value = found_split_value.lstrip() +- if not found_split_value: ++ if found_name == name: ++ found_raw_value = found_raw_value.lower() ++ for found_split_value in found_raw_value.split(b","): ++ found_split_value = found_split_value.strip() ++ if found_split_value: + out.append(found_split_value) + return out + +@@ -234,7 +269,10 @@ + + + def has_expect_100_continue(request: "Request") -> bool: +- if request.http_version <= b"1.1": +- return True ++ # https://tools.ietf.org/html/rfc7231#section-5.1.1 ++ # "A server that receives a 100-continue expectation in an HTTP/1.0 request ++ # MUST ignore that expectation." ++ if request.http_version < b"1.1": ++ return False + expect = get_comma_header(request.headers, b"expect") +- return b"100-continue" not in expect ++ return b"100-continue" in expect +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..c471dc54dac9a47ba349eb92cf5ed2b6e66b1646 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..dcd05a2b5cacb6dc67b97ee9ebe1abf60165d7a9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/canaries/first-hunk-only.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_headers.py b/h11/_headers.py +index 2d203586ec3941fa50a1d05ca58a2ca3a2675ae1..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -103,13 +103,13 @@ + self._full_items = full_items + + def __bool__(self) -> bool: +- return len(self._full_items) > 1 ++ return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: +- return len(self._full_items) - 1 ++ return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4fir9h4i/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..8cbca7104e3771bae249964eb4afd763087423d2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "0932aed329d9a41e3a456a7d1aff38135378c957287e685a102feadc43a0b8b5", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "240a670f6bb35e9993ebdc28a7b51c163f9c0b243c2ed5c208a8a32ef52714a6", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "ca89a9cc8284e28bde5dbac3f27fd2a309c1855991f32ffef630ff52fe6aba0a", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea", + "source_completion_sha256": "09e2d54e7c022fcf435231e54fa6913869625b39a2965b1de3fee637dadbefa5", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "3a99ee2beebe8a6c7949bb39422212a5450631262b7910b77291b011606b2574", + "is_fork": true, + "learner_path": "tasks/1d8952faf3c03b44f54bccd9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "f1486489a1787effdfb6a09fe8cc77506f90a371258102ba76331f2b8506d719", + "provenance_path": "tasks/1d8952faf3c03b44f54bccd9/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "dfcd4f8cccf69936b0ea744b5465f4eddd09aebb", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "task_sha256": "3b95118a72bbf8b362455868a1ed84802cead98a9719917c527c87b3b40ec2c7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84807403bc64620124d28f972fc754175ee07b27 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/instruction.md @@ -0,0 +1,31 @@ +ReceiveBuffer operations broken after recent changes + +#### Description + +The ReceiveBuffer class is not working correctly. Basic operations like adding data and extracting lines are producing unexpected results. + +#### Steps/Code to Reproduce + +```python +from h11._receivebuffer import ReceiveBuffer + +# Basic buffer operations fail +buf = ReceiveBuffer() +buf += b"Hello\r\nWorld\r\n" +print(f"Buffer length: {len(buf)}") # Expected: 13, but gets wrong value +print(f"Buffer data: {bytes(buf)}") # Expected: b"Hello\r\nWorld\r\n", but gets reversed + +# Line extraction doesn't work +lines = buf.maybe_extract_lines() +print(f"Extracted lines: {lines}") # Should extract lines properly + +# In-place addition returns None instead of self +result = buf += b"more data" +print(f"Addition result: {result}") # Expected: ReceiveBuffer object, but gets None +``` + +The buffer seems to be reversing data and returning incorrect lengths. Line extraction is also broken because it's looking for the wrong line ending sequence. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1c0c48d68aede510f90a4f3beabf5bb21cbe5cdf --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "dfcd4f8cccf69936b0ea744b5465f4eddd09aebb", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_io.py", + "h11/tests/test_receivebuffer.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": [ + "h11/_receivebuffer.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 997544, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "3a99ee2beebe8a6c7949bb39422212a5450631262b7910b77291b011606b2574", + "is_fork": true, + "learner_path": "tasks/1d8952faf3c03b44f54bccd9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "f1486489a1787effdfb6a09fe8cc77506f90a371258102ba76331f2b8506d719", + "provenance_path": "tasks/1d8952faf3c03b44f54bccd9/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "dfcd4f8cccf69936b0ea744b5465f4eddd09aebb", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "task_sha256": "3b95118a72bbf8b362455868a1ed84802cead98a9719917c527c87b3b40ec2c7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..b01be93f7463c4891f98faf5adfa527e5ad50919 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "0932aed329d9a41e3a456a7d1aff38135378c957287e685a102feadc43a0b8b5", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "09e2d54e7c022fcf435231e54fa6913869625b39a2965b1de3fee637dadbefa5", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "bf518da24e8eafb3482cf8f1357db74b69733066d089833adaffd734fad742fa", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "3a99ee2beebe8a6c7949bb39422212a5450631262b7910b77291b011606b2574", + "is_fork": true, + "learner_path": "tasks/1d8952faf3c03b44f54bccd9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "f1486489a1787effdfb6a09fe8cc77506f90a371258102ba76331f2b8506d719", + "provenance_path": "tasks/1d8952faf3c03b44f54bccd9/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a6e53e2d2c4e1365a9d7218edccf5ff37adb56ea", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "dfcd4f8cccf69936b0ea744b5465f4eddd09aebb", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4pj8390q", + "task_sha256": "3b95118a72bbf8b362455868a1ed84802cead98a9719917c527c87b3b40ec2c7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..8dd38c1481e632cd6c270b50f6f40469947a672f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/provided-gold.diff @@ -0,0 +1,48 @@ +diff --git a/h11/_receivebuffer.py b/h11/_receivebuffer.py +index 17e3685447ce5d2a7f66550db3b554d3a18846a9..e5c4e08a56f5081e87103f38b4add6ce1b730204 100644 +--- a/h11/_receivebuffer.py ++++ b/h11/_receivebuffer.py +@@ -51,18 +51,18 @@ + self._multiple_lines_search = 0 + + def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": +- self._data = byteslike + self._data +- return None ++ self._data += byteslike ++ return self + + def __bool__(self) -> bool: + return bool(len(self)) + + def __len__(self) -> int: +- return len(self._data) - 1 ++ return len(self._data) + + # for @property unprocessed_data + def __bytes__(self) -> bytes: +- return bytes(self._data[::-1]) ++ return bytes(self._data) + + def _extract(self, count: int) -> bytearray: + # extracting an initial slice of the data buffer and return it +@@ -88,14 +88,16 @@ + """ + Extract the first line, if it is completed in the buffer. + """ +- search_start_index = max(0, self._next_line_search) +- partial_idx = self._data.find(b"\n\r", search_start_index) ++ # Only search in buffer space that we've not already looked at. ++ search_start_index = max(0, self._next_line_search - 1) ++ partial_idx = self._data.find(b"\r\n", search_start_index) + + if partial_idx == -1: +- self._next_line_search = len(self._data) - 1 ++ self._next_line_search = len(self._data) + return None + +- idx = partial_idx + 1 ++ # + 2 is to compensate len(b"\r\n") ++ idx = partial_idx + 2 + + return self._extract(idx) + diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c5c7289d0b9e926b2df4356f8f67b6aba59deb69 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/solution/solve.sh @@ -0,0 +1,54 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_receivebuffer.py b/h11/_receivebuffer.py +index 17e3685447ce5d2a7f66550db3b554d3a18846a9..e5c4e08a56f5081e87103f38b4add6ce1b730204 100644 +--- a/h11/_receivebuffer.py ++++ b/h11/_receivebuffer.py +@@ -51,18 +51,18 @@ + self._multiple_lines_search = 0 + + def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": +- self._data = byteslike + self._data +- return None ++ self._data += byteslike ++ return self + + def __bool__(self) -> bool: + return bool(len(self)) + + def __len__(self) -> int: +- return len(self._data) - 1 ++ return len(self._data) + + # for @property unprocessed_data + def __bytes__(self) -> bytes: +- return bytes(self._data[::-1]) ++ return bytes(self._data) + + def _extract(self, count: int) -> bytearray: + # extracting an initial slice of the data buffer and return it +@@ -88,14 +88,16 @@ + """ + Extract the first line, if it is completed in the buffer. + """ +- search_start_index = max(0, self._next_line_search) +- partial_idx = self._data.find(b"\n\r", search_start_index) ++ # Only search in buffer space that we've not already looked at. ++ search_start_index = max(0, self._next_line_search - 1) ++ partial_idx = self._data.find(b"\r\n", search_start_index) + + if partial_idx == -1: +- self._next_line_search = len(self._data) - 1 ++ self._next_line_search = len(self._data) + return None + +- idx = partial_idx + 1 ++ # + 2 is to compensate len(b"\r\n") ++ idx = partial_idx + 2 + + return self._extract(idx) + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..ac6063a3c3bb986d8d65cd98a4c4fe16a4e0c2ae --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..0f826c35658267920f47294cef706a7c94b8dff5 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/canaries/first-hunk-only.sh @@ -0,0 +1,33 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_receivebuffer.py b/h11/_receivebuffer.py +index 17e3685447ce5d2a7f66550db3b554d3a18846a9..e5c4e08a56f5081e87103f38b4add6ce1b730204 100644 +--- a/h11/_receivebuffer.py ++++ b/h11/_receivebuffer.py +@@ -51,18 +51,18 @@ + self._multiple_lines_search = 0 + + def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": +- self._data = byteslike + self._data +- return None ++ self._data += byteslike ++ return self + + def __bool__(self) -> bool: + return bool(len(self)) + + def __len__(self) -> int: +- return len(self._data) - 1 ++ return len(self._data) + + # for @property unprocessed_data + def __bytes__(self) -> bytes: +- return bytes(self._data[::-1]) ++ return bytes(self._data) + + def _extract(self, count: int) -> bytearray: + # extracting an initial slice of the data buffer and return it +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4pj8390q/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f4d2c0baf4da85f48f100d287d945ef88160e93d --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "4679c3ebeb0a26fddd11f73b15a7cf6815e067eafe66d14249a90e4a12416471", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "bb9c5747a30b700a8fd5700835145e1f1b05b321414e5f355a5c640df11ca201", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "3a65cc613b51b22b1c0e5f7332d858e98d0273bcc889818e4fa400dd2c0e2dbc", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "0415e8b80f28f07840198d227a6a5d42936c969d", + "source_completion_sha256": "30fd1b3970a926bc8d885ac28bf6b8408a0cd99879cf74f1fa774063bae56ecf", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0cd48fdb5c770a1d730d253daac11db558de7c8e772b158fe78553ee66a2c654", + "is_fork": true, + "learner_path": "tasks/c34435b2bcbb7459af220896/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/0415e8b80f28f07840198d227a6a5d42936c969d/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "ffc6cc642f8cee89f672e20727f0314307914def40a8ce73b8279a2515ae98e7", + "provenance_path": "tasks/c34435b2bcbb7459af220896/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "0415e8b80f28f07840198d227a6a5d42936c969d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1ea8b0b332b66700ac7b19adf5f4d71dd311c821", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "task_sha256": "74be1ffbf65a35738b88e8b964f4c8d4706b137535127f6db17b750683490374", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..905cdebb41ffaad22d2663f3c091f2cb7e3b8ff3 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/instruction.md @@ -0,0 +1,31 @@ +Headers class returns incorrect length and boolean values + +#### Description + +The Headers class is returning incorrect values for `len()` and boolean evaluation. When creating Headers with items, the length is off by one and boolean evaluation behaves unexpectedly. + +#### Steps/Code to Reproduce + +```python +from h11._headers import Headers + +# Create headers with some items +headers = Headers([(b'host', b'example.com'), (b'content-type', b'text/html')]) + +# Length should be 2 but returns 1 +print(f"Expected length: 2, Actual length: {len(headers)}") + +# Boolean evaluation should be True for non-empty headers +print(f"Expected bool: True, Actual bool: {bool(headers)}") + +# Empty headers case +empty_headers = Headers([]) +print(f"Empty headers length: {len(empty_headers)}") +print(f"Empty headers bool: {bool(empty_headers)}") +``` + +The length calculation appears to be subtracting 1 from the actual number of items, and the boolean evaluation is checking if length > 1 instead of just checking if there are any items. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..d25105b57a3e68a59987244fb0badd2980c289e8 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "PASS_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "1ea8b0b332b66700ac7b19adf5f4d71dd311c821", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "0415e8b80f28f07840198d227a6a5d42936c969d" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_events.py", + "h11/tests/test_headers.py", + "h11/tests/test_helpers.py", + "h11/tests/test_io.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": [ + "h11/_headers.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 990099, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0cd48fdb5c770a1d730d253daac11db558de7c8e772b158fe78553ee66a2c654", + "is_fork": true, + "learner_path": "tasks/c34435b2bcbb7459af220896/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/0415e8b80f28f07840198d227a6a5d42936c969d/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "ffc6cc642f8cee89f672e20727f0314307914def40a8ce73b8279a2515ae98e7", + "provenance_path": "tasks/c34435b2bcbb7459af220896/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "0415e8b80f28f07840198d227a6a5d42936c969d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1ea8b0b332b66700ac7b19adf5f4d71dd311c821", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "task_sha256": "74be1ffbf65a35738b88e8b964f4c8d4706b137535127f6db17b750683490374", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..13844195fe73cca8f4ee0b8867e87054e82b8ae8 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "4679c3ebeb0a26fddd11f73b15a7cf6815e067eafe66d14249a90e4a12416471", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/0415e8b80f28f07840198d227a6a5d42936c969d/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "30fd1b3970a926bc8d885ac28bf6b8408a0cd99879cf74f1fa774063bae56ecf", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "a5b3b8d320c3cbb81b7330e17f5ffa66665d9c52fd076099a7e8d94984e6b09c", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "0cd48fdb5c770a1d730d253daac11db558de7c8e772b158fe78553ee66a2c654", + "is_fork": true, + "learner_path": "tasks/c34435b2bcbb7459af220896/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/0415e8b80f28f07840198d227a6a5d42936c969d/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "ffc6cc642f8cee89f672e20727f0314307914def40a8ce73b8279a2515ae98e7", + "provenance_path": "tasks/c34435b2bcbb7459af220896/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "0415e8b80f28f07840198d227a6a5d42936c969d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1ea8b0b332b66700ac7b19adf5f4d71dd311c821", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__4yhofn1l", + "task_sha256": "74be1ffbf65a35738b88e8b964f4c8d4706b137535127f6db17b750683490374", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..7a3e82fa282376fcad877ec147a4caf8b77e595e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/provided-gold.diff @@ -0,0 +1,37 @@ +diff --git a/h11/_headers.py b/h11/_headers.py +index fb95d7848bb1ef39aec7b29df8210e63789b6500..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -103,13 +103,13 @@ + self._full_items = full_items + + def __bool__(self) -> bool: +- return len(self._full_items) > 1 ++ return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: +- return len(self._full_items) - 1 ++ return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) +@@ -268,7 +268,11 @@ + return normalize_and_validate(new_headers) + + +-def has_expect_100_continue(request: 'Request') ->bool: +- """Return whether this request has an Expect: 100-continue header.""" +- expect_values = get_comma_header(request.headers, b"expect") +- return b"100-continue" in expect_values +\ No newline at end of file ++def has_expect_100_continue(request: "Request") -> bool: ++ # https://tools.ietf.org/html/rfc7231#section-5.1.1 ++ # "A server that receives a 100-continue expectation in an HTTP/1.0 request ++ # MUST ignore that expectation." ++ if request.http_version < b"1.1": ++ return False ++ expect = get_comma_header(request.headers, b"expect") ++ return b"100-continue" in expect diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c1bc32b55b2bb5dcd82064020157e57a6a7afc4b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/solution/solve.sh @@ -0,0 +1,43 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_headers.py b/h11/_headers.py +index fb95d7848bb1ef39aec7b29df8210e63789b6500..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -103,13 +103,13 @@ + self._full_items = full_items + + def __bool__(self) -> bool: +- return len(self._full_items) > 1 ++ return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: +- return len(self._full_items) - 1 ++ return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) +@@ -268,7 +268,11 @@ + return normalize_and_validate(new_headers) + + +-def has_expect_100_continue(request: 'Request') ->bool: +- """Return whether this request has an Expect: 100-continue header.""" +- expect_values = get_comma_header(request.headers, b"expect") +- return b"100-continue" in expect_values +\ No newline at end of file ++def has_expect_100_continue(request: "Request") -> bool: ++ # https://tools.ietf.org/html/rfc7231#section-5.1.1 ++ # "A server that receives a 100-continue expectation in an HTTP/1.0 request ++ # MUST ignore that expectation." ++ if request.http_version < b"1.1": ++ return False ++ expect = get_comma_header(request.headers, b"expect") ++ return b"100-continue" in expect +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..13ca589a0961ab65eca164d1ed59fc56cfa62d43 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "pass-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..34bd66f3e3fcd94dfbc0dc8b5d8f8eb19e0509ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/canaries/first-hunk-only.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_headers.py b/h11/_headers.py +index fb95d7848bb1ef39aec7b29df8210e63789b6500..b97d020b634a9f47f5ae6aa3b30e2bd13a6c48c4 100644 +--- a/h11/_headers.py ++++ b/h11/_headers.py +@@ -103,13 +103,13 @@ + self._full_items = full_items + + def __bool__(self) -> bool: +- return len(self._full_items) > 1 ++ return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: +- return len(self._full_items) - 1 ++ return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__4yhofn1l/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..2a9026f86708aa9d1ff17b08de84a5696956bfa6 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "ee88a2b46ea472b0d5c6cb296d08565b136644cee82b352f1298a53d49050d81", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "7091bff9fb62a61f02afd8129ed7f79b50124820448513f5a6779d9243b0cc2b", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "937f69f3a07417e5feea44225a6356267320e9306a51c6b66295ffa2eaedf847", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc", + "source_completion_sha256": "a3e9a8a78ad70955c9eb2d8eb8c6633a26a850dcd7905c2009643984cb40b567", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "e1d7d8aca003eb5807628e126a4f8de9045f1f1fd954cc30e15799fa7b803cc8", + "is_fork": true, + "learner_path": "tasks/885ac8653c589e1b48882834/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "0344cf1f01e3837ee932af72fb521b767ea7abe5915b17604ee8cd0a07a2dbc4", + "provenance_path": "tasks/885ac8653c589e1b48882834/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "941b3a7156f3d544da0b05a2205b74b9773c4b96", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "task_sha256": "1c53d440c030314a96813ab494cff836e826c5b316c093ac94364cef6ba04a3a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c45e5690afdd66b7cfa5fc73ccccf6097c577cd6 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/instruction.md @@ -0,0 +1,75 @@ +# HTTP/1.1 Connection State Management Issues + +I've encountered some serious issues with the h11 library's connection state management. The library seems to be incorrectly handling state transitions and data processing, causing HTTP connections to fail in various ways. + +## Problem Description + +When using the h11 library to handle HTTP connections, I'm experiencing multiple failures in both client and server roles. The issues appear to be related to how the connection state is tracked and how data is processed. + +## Steps to Reproduce + +Here's a simple example that demonstrates one of the issues: + +```python +from h11 import Connection, CLIENT, Request, EndOfMessage, Data, NEED_DATA + +# Create a client connection +conn = Connection(CLIENT) + +# Send a request +conn.send(Request(method='GET', target='/', headers=[('Host', 'example.com')])) +conn.send(EndOfMessage()) + +# Receive a response +conn.receive_data(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n1234567890') + +# Try to get the response events +event = conn.next_event() # This should return a Response object +print(event) # But it fails with an AttributeError +``` + +I've also noticed issues with chunked encoding: + +```python +from h11 import Connection, SERVER, Request, Data, EndOfMessage + +# Create a server connection +conn = Connection(SERVER) + +# Receive a chunked request +conn.receive_data(b'POST / HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\n\r\n') +conn.next_event() # Returns Request +conn.next_event() # Returns NEED_DATA + +# Receive a chunk +conn.receive_data(b'8\r\n012345') +event = conn.next_event() # Should return Data with '012345' +print(event.data) # But fails with an AttributeError +``` + +## Expected Behavior + +- The connection should properly track state for both client and server roles +- `next_event()` should correctly return events based on received data +- Chunked encoding should work properly +- Connection state transitions should follow the HTTP/1.1 specification + +## Actual Behavior + +- Getting AttributeError when trying to access connection states +- Incorrect handling of data in the receive buffer +- Issues with state transitions when processing events +- Problems with chunked encoding and content-length handling + +## Environment + +- h11 version: 0.14.0 +- Python version: 3.10.15 + +This issue is causing significant problems in my application that relies on h11 for HTTP communication. Any help would be appreciated! + + + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..c1b0f2c4983b452630be6574735de28b38d34817 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "941b3a7156f3d544da0b05a2205b74b9773c4b96", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_io.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.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": [ + "h11/_connection.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1016210, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "e1d7d8aca003eb5807628e126a4f8de9045f1f1fd954cc30e15799fa7b803cc8", + "is_fork": true, + "learner_path": "tasks/885ac8653c589e1b48882834/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "0344cf1f01e3837ee932af72fb521b767ea7abe5915b17604ee8cd0a07a2dbc4", + "provenance_path": "tasks/885ac8653c589e1b48882834/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "941b3a7156f3d544da0b05a2205b74b9773c4b96", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "task_sha256": "1c53d440c030314a96813ab494cff836e826c5b316c093ac94364cef6ba04a3a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f3f3df77b5dbffbc7f4fd39e8e4526dffc6c3b1b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "ee88a2b46ea472b0d5c6cb296d08565b136644cee82b352f1298a53d49050d81", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "a3e9a8a78ad70955c9eb2d8eb8c6633a26a850dcd7905c2009643984cb40b567", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "df1213825566f04a7a6c7e3210372313a0beda9516627148da974cb74d412eb3", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "e1d7d8aca003eb5807628e126a4f8de9045f1f1fd954cc30e15799fa7b803cc8", + "is_fork": true, + "learner_path": "tasks/885ac8653c589e1b48882834/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "0344cf1f01e3837ee932af72fb521b767ea7abe5915b17604ee8cd0a07a2dbc4", + "provenance_path": "tasks/885ac8653c589e1b48882834/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "fa7fcc5c1de92fb3eebfa8c681e5d021d48094bc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "941b3a7156f3d544da0b05a2205b74b9773c4b96", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4", + "task_sha256": "1c53d440c030314a96813ab494cff836e826c5b316c093ac94364cef6ba04a3a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..9702482287a33ff550971952d1ed5a3b485dd2e8 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/provided-gold.diff @@ -0,0 +1,70 @@ +diff --git a/h11/_connection.py b/h11/_connection.py +index 94c86732b09e60f3ae0e704b42c3d9c077e05434..e37d82a82a882c072cb938a90eb4486b51cdad99 100644 +--- a/h11/_connection.py ++++ b/h11/_connection.py +@@ -212,14 +212,14 @@ + See :ref:`state-machine` for details. + + """ +- return dict(reversed(self._cstate.states)) ++ return dict(self._cstate.states) + + @property + def our_state(self) -> Type[Sentinel]: + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ +- return self._cstate.states.get(self.our_role, self._cstate.default_state) ++ return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: +@@ -411,21 +411,29 @@ + self, + ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + state = self.their_state +- if state is DONE and not self._receive_buffer: ++ # We don't pause immediately when they enter DONE, because even in ++ # DONE state we can still process a ConnectionClosed() event. But ++ # if we have data in our buffer, then we definitely aren't getting ++ # a ConnectionClosed() immediately and we need to pause. ++ if state is DONE and self._receive_buffer: + return PAUSED +- if state is MIGHT_SWITCH_PROTOCOL and state is SWITCHED_PROTOCOL: ++ if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: + return PAUSED + assert self._reader is not None + event = self._reader(self._receive_buffer) +- if event is not None: +- if self._receive_buffer and self._receive_buffer_closed: ++ if event is None: ++ if not self._receive_buffer and self._receive_buffer_closed: ++ # In some unusual cases (basically just HTTP/1.0 bodies), EOF ++ # triggers an actual protocol event; in that case, we want to ++ # return that event, and then the state will change and we'll ++ # get called again to generate the actual ConnectionClosed(). + if hasattr(self._reader, "read_eof"): + event = self._reader.read_eof() + else: + event = ConnectionClosed() +- if event is not None: ++ if event is None: + event = NEED_DATA +- return event ++ return event # type: ignore[no-any-return] + + def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + """Parse the next event out of our receive buffer, update our internal +@@ -528,10 +536,10 @@ + + """ + data_list = self.send_with_data_passthrough(event) +- if data_list is not None: ++ if data_list is None: + return None + else: +- return b"".join(reversed(data_list)) ++ return b"".join(data_list) + + def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: + """Identical to :meth:`send`, except that in situations where diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d44ba9132ba45a35396897f1e1c092712ba9e9c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/solution/solve.sh @@ -0,0 +1,76 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_connection.py b/h11/_connection.py +index 94c86732b09e60f3ae0e704b42c3d9c077e05434..e37d82a82a882c072cb938a90eb4486b51cdad99 100644 +--- a/h11/_connection.py ++++ b/h11/_connection.py +@@ -212,14 +212,14 @@ + See :ref:`state-machine` for details. + + """ +- return dict(reversed(self._cstate.states)) ++ return dict(self._cstate.states) + + @property + def our_state(self) -> Type[Sentinel]: + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ +- return self._cstate.states.get(self.our_role, self._cstate.default_state) ++ return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: +@@ -411,21 +411,29 @@ + self, + ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + state = self.their_state +- if state is DONE and not self._receive_buffer: ++ # We don't pause immediately when they enter DONE, because even in ++ # DONE state we can still process a ConnectionClosed() event. But ++ # if we have data in our buffer, then we definitely aren't getting ++ # a ConnectionClosed() immediately and we need to pause. ++ if state is DONE and self._receive_buffer: + return PAUSED +- if state is MIGHT_SWITCH_PROTOCOL and state is SWITCHED_PROTOCOL: ++ if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: + return PAUSED + assert self._reader is not None + event = self._reader(self._receive_buffer) +- if event is not None: +- if self._receive_buffer and self._receive_buffer_closed: ++ if event is None: ++ if not self._receive_buffer and self._receive_buffer_closed: ++ # In some unusual cases (basically just HTTP/1.0 bodies), EOF ++ # triggers an actual protocol event; in that case, we want to ++ # return that event, and then the state will change and we'll ++ # get called again to generate the actual ConnectionClosed(). + if hasattr(self._reader, "read_eof"): + event = self._reader.read_eof() + else: + event = ConnectionClosed() +- if event is not None: ++ if event is None: + event = NEED_DATA +- return event ++ return event # type: ignore[no-any-return] + + def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + """Parse the next event out of our receive buffer, update our internal +@@ -528,10 +536,10 @@ + + """ + data_list = self.send_with_data_passthrough(event) +- if data_list is not None: ++ if data_list is None: + return None + else: +- return b"".join(reversed(data_list)) ++ return b"".join(data_list) + + def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: + """Identical to :meth:`send`, except that in situations where +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..61e2a3cd8c03c9539f1aa05dde6a6e0c26c807dd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..bbfdbee028d6fd0f4545108e680bac5777dced59 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/canaries/first-hunk-only.sh @@ -0,0 +1,27 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_connection.py b/h11/_connection.py +index 94c86732b09e60f3ae0e704b42c3d9c077e05434..e37d82a82a882c072cb938a90eb4486b51cdad99 100644 +--- a/h11/_connection.py ++++ b/h11/_connection.py +@@ -212,14 +212,14 @@ + See :ref:`state-machine` for details. + + """ +- return dict(reversed(self._cstate.states)) ++ return dict(self._cstate.states) + + @property + def our_state(self) -> Type[Sentinel]: + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ +- return self._cstate.states.get(self.our_role, self._cstate.default_state) ++ return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5bgrd1b4/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e4f654bd39bd9c6a37e82769b19943986e35417d --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "a76739787b04b64ce0bd54842ac79ab5b1aebe16e856f8259db2b4519557cab3", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "96f569b9c320fa3cb642ea9fafe73f091f781ff6bdeac88e072604dccc2843d1", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "30f52e7549f7532af92370b46ba2a7d59108b95b17dc4b1735841c0ed4012c5b", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "8a7494a784192f78cf62c23bd6827ea72d8b28fa", + "source_completion_sha256": "1eb967956d775b1832759520f3853ee2f1e30ff56657732b5c5418cd182c2ed6", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "1d41ef9934566b6654c04aa3dc304e3c2d71fb1f5ee1c31939556e4c0c98a0e1", + "is_fork": true, + "learner_path": "tasks/b49b7b84fef8199886075f59/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/8a7494a784192f78cf62c23bd6827ea72d8b28fa/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "8a53f5a6f1af90d4fab4906bab2379a8203cd4cde7424c5aa56654f5d7aaa47b", + "provenance_path": "tasks/b49b7b84fef8199886075f59/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "8a7494a784192f78cf62c23bd6827ea72d8b28fa", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5aba2bc3542057fd522112060d5527608051490e", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "task_sha256": "cea9bf1670100784a4920739fa87163fcca869df40e21f9dacd010fa1e5e47d0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89ffbedfb881941060ef21c77e48d586bb1f6746 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/instruction.md @@ -0,0 +1,49 @@ +Host header ordering broken in HTTP requests + +#### Description + +When sending HTTP requests, the Host header is no longer being written first as required by RFC 7230. Instead, it appears to be written last, which breaks compatibility with some servers that expect proper header ordering. + +#### Steps/Code to Reproduce + +```python +import h11 + +# Create a simple HTTP request +conn = h11.Connection(h11.CLIENT) +request = h11.Request( + method="GET", + target="/", + headers=[ + ("User-Agent", "test-client"), + ("Host", "example.com"), + ("Accept", "text/html") + ] +) + +# Send the request and check the raw output +data = conn.send(request) +print(data) +``` + +Expected output should have Host header first: +``` +GET / HTTP/1.1\r\n +Host: example.com\r\n +User-Agent: test-client\r\n +Accept: text/html\r\n +``` + +But actual output has Host header last: +``` +GET / HTTP/1.1\r\n +User-Agent: test-client\r\n +Accept: text/html\r\n +Host: example.com\r\n +``` + +This violates RFC 7230 which states that the Host field should be the first header field following the request line for proper HTTP/1.1 compliance. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..6c6aa315085bcdac7e4fa9068579f52785729cef --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_host_comes_first" + ], + "PASS_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "5aba2bc3542057fd522112060d5527608051490e", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "8a7494a784192f78cf62c23bd6827ea72d8b28fa" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_io.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": [ + "h11/_writers.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1000806, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "1d41ef9934566b6654c04aa3dc304e3c2d71fb1f5ee1c31939556e4c0c98a0e1", + "is_fork": true, + "learner_path": "tasks/b49b7b84fef8199886075f59/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/8a7494a784192f78cf62c23bd6827ea72d8b28fa/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "8a53f5a6f1af90d4fab4906bab2379a8203cd4cde7424c5aa56654f5d7aaa47b", + "provenance_path": "tasks/b49b7b84fef8199886075f59/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "8a7494a784192f78cf62c23bd6827ea72d8b28fa", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5aba2bc3542057fd522112060d5527608051490e", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "task_sha256": "cea9bf1670100784a4920739fa87163fcca869df40e21f9dacd010fa1e5e47d0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..84fd3eb826ffd98d362392974e0591c42a0c967d --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "a76739787b04b64ce0bd54842ac79ab5b1aebe16e856f8259db2b4519557cab3", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/8a7494a784192f78cf62c23bd6827ea72d8b28fa/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "1eb967956d775b1832759520f3853ee2f1e30ff56657732b5c5418cd182c2ed6", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "37fee7cdb3c511ef8715dd6771a24ffa5c571c66de923a1e822ece1a82e3b5cc", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "1d41ef9934566b6654c04aa3dc304e3c2d71fb1f5ee1c31939556e4c0c98a0e1", + "is_fork": true, + "learner_path": "tasks/b49b7b84fef8199886075f59/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/8a7494a784192f78cf62c23bd6827ea72d8b28fa/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "8a53f5a6f1af90d4fab4906bab2379a8203cd4cde7424c5aa56654f5d7aaa47b", + "provenance_path": "tasks/b49b7b84fef8199886075f59/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "8a7494a784192f78cf62c23bd6827ea72d8b28fa", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5aba2bc3542057fd522112060d5527608051490e", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5qwccxor", + "task_sha256": "cea9bf1670100784a4920739fa87163fcca869df40e21f9dacd010fa1e5e47d0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..33a2ba0394c8c98a4a84ac13dca81477af928722 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/provided-gold.diff @@ -0,0 +1,34 @@ +diff --git a/h11/_writers.py b/h11/_writers.py +index e2c036d6cc659c3f697d89f45b7833c1252293fd..939cdb912a9debaea07fbf3a9ac04549c44d077c 100644 +--- a/h11/_writers.py ++++ b/h11/_writers.py +@@ -20,12 +20,15 @@ + + + def write_headers(headers: Headers, write: Writer) -> None: ++ # "Since the Host field-value is critical information for handling a ++ # request, a user agent SHOULD generate Host as the first header field ++ # following the request-line." - RFC 7230 + raw_items = headers._full_items + for raw_name, name, value in raw_items: +- if name != b"host": ++ if name == b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + for raw_name, name, value in raw_items: +- if name == b"host": ++ if name != b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + write(b"\r\n") + +@@ -89,9 +92,9 @@ + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: +- if self._length == 0: ++ if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") +- if not headers: ++ if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d886961d28e286166b0b418838f9b5e6331b255a --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/solution/solve.sh @@ -0,0 +1,40 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_writers.py b/h11/_writers.py +index e2c036d6cc659c3f697d89f45b7833c1252293fd..939cdb912a9debaea07fbf3a9ac04549c44d077c 100644 +--- a/h11/_writers.py ++++ b/h11/_writers.py +@@ -20,12 +20,15 @@ + + + def write_headers(headers: Headers, write: Writer) -> None: ++ # "Since the Host field-value is critical information for handling a ++ # request, a user agent SHOULD generate Host as the first header field ++ # following the request-line." - RFC 7230 + raw_items = headers._full_items + for raw_name, name, value in raw_items: +- if name != b"host": ++ if name == b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + for raw_name, name, value in raw_items: +- if name == b"host": ++ if name != b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + write(b"\r\n") + +@@ -89,9 +92,9 @@ + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: +- if self._length == 0: ++ if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") +- if not headers: ++ if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..b18b733f00408b4a2d0af951a49451875bdef10f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_host_comes_first" + ], + "pass-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc19b3ad64e187bfe63a24a1f807853c0e027b58 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/canaries/first-hunk-only.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_writers.py b/h11/_writers.py +index e2c036d6cc659c3f697d89f45b7833c1252293fd..939cdb912a9debaea07fbf3a9ac04549c44d077c 100644 +--- a/h11/_writers.py ++++ b/h11/_writers.py +@@ -20,12 +20,15 @@ + + + def write_headers(headers: Headers, write: Writer) -> None: ++ # "Since the Host field-value is critical information for handling a ++ # request, a user agent SHOULD generate Host as the first header field ++ # following the request-line." - RFC 7230 + raw_items = headers._full_items + for raw_name, name, value in raw_items: +- if name != b"host": ++ if name == b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + for raw_name, name, value in raw_items: +- if name == b"host": ++ if name != b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + write(b"\r\n") + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5qwccxor/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..06ad831260679b2dbd54e67659efc6def0b34f30 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "7d31fcbf31fc92a2c559f74bdf3b7c6ee6c57ab68983690eed4690c8761461e3", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "16d772f699e454bf76881d74bcee1565091b901bfb522f89e71842c8e952aa1c", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "bc762b0d4ecef721778487ed7210f2916b4f9fc985445a9b52f32c65e9986aed", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "ec922f9766170e147bcdb728d14aa932f2bfe449", + "source_completion_sha256": "21b552afe5a94c485d525d64e113452616882bfe8608515343124e7e1c8de0a2", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "a506c920da2a55795d7618132fa6e34f63fbe8838cc24f0d15e7dd0020343d59", + "is_fork": true, + "learner_path": "tasks/21da14e0efeb67024a027fa6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/ec922f9766170e147bcdb728d14aa932f2bfe449/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "e01b67c8baa7dcc6b195dae19e57fc3364ec7e3c87ea3982b924f63604905725", + "provenance_path": "tasks/21da14e0efeb67024a027fa6/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ec922f9766170e147bcdb728d14aa932f2bfe449", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6f713685e61aa15c8b1a9af7398e60ac1f88a2a1", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "task_sha256": "b993f7c97f9e3b956f38ab3c8d38feb2a9b6a6f15d219117bd3bef8d9749f25e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b18358a121c9f746b19975546c7f8bf185294fc9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/instruction.md @@ -0,0 +1,33 @@ +Connection.send() returns None instead of bytes when data_list is not None + +#### Description + +The `Connection.send()` method is returning `None` when it should return bytes, causing issues with HTTP message serialization. + +#### Steps/Code to Reproduce + +```python +import h11 + +# Create a connection and try to send a simple request +c = h11.Connection(h11.CLIENT) +request = h11.Request(method='GET', target='/', headers=[('Host', 'example.com')]) +result = c.send(request) +print(f"Expected bytes, got: {type(result)} - {result}") + +# Try with server response +c = h11.Connection(h11.SERVER) +c.receive_data(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n') +c.next_event() # Request +c.next_event() # EndOfMessage + +response = h11.Response(status_code=200, headers=[]) +result = c.send(response) +print(f"Expected bytes, got: {type(result)} - {result}") +``` + +The `send()` method should return the serialized HTTP message as bytes, but instead returns `None` in cases where it should return actual data. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..33e4ecbad4e7044f66a15ca5ecb6dfd31fc8d3cf --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "6f713685e61aa15c8b1a9af7398e60ac1f88a2a1", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "ec922f9766170e147bcdb728d14aa932f2bfe449" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_io.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.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": [ + "h11/_connection.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1017436, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "a506c920da2a55795d7618132fa6e34f63fbe8838cc24f0d15e7dd0020343d59", + "is_fork": true, + "learner_path": "tasks/21da14e0efeb67024a027fa6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/ec922f9766170e147bcdb728d14aa932f2bfe449/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "e01b67c8baa7dcc6b195dae19e57fc3364ec7e3c87ea3982b924f63604905725", + "provenance_path": "tasks/21da14e0efeb67024a027fa6/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ec922f9766170e147bcdb728d14aa932f2bfe449", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6f713685e61aa15c8b1a9af7398e60ac1f88a2a1", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "task_sha256": "b993f7c97f9e3b956f38ab3c8d38feb2a9b6a6f15d219117bd3bef8d9749f25e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..205a0f53f45270b6b1c0aaad210fd33401aa3f40 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "7d31fcbf31fc92a2c559f74bdf3b7c6ee6c57ab68983690eed4690c8761461e3", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/ec922f9766170e147bcdb728d14aa932f2bfe449/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "21b552afe5a94c485d525d64e113452616882bfe8608515343124e7e1c8de0a2", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "6c8da7d24a3cbf98624b2a42fa38c44649918bf0389795732dfc183ab4903638", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "a506c920da2a55795d7618132fa6e34f63fbe8838cc24f0d15e7dd0020343d59", + "is_fork": true, + "learner_path": "tasks/21da14e0efeb67024a027fa6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/ec922f9766170e147bcdb728d14aa932f2bfe449/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "e01b67c8baa7dcc6b195dae19e57fc3364ec7e3c87ea3982b924f63604905725", + "provenance_path": "tasks/21da14e0efeb67024a027fa6/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ec922f9766170e147bcdb728d14aa932f2bfe449", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6f713685e61aa15c8b1a9af7398e60ac1f88a2a1", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__5ug1a88v", + "task_sha256": "b993f7c97f9e3b956f38ab3c8d38feb2a9b6a6f15d219117bd3bef8d9749f25e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..dfc8ac73e48e52868a92b72efd7643ee700c4907 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/provided-gold.diff @@ -0,0 +1,26 @@ +diff --git a/h11/_connection.py b/h11/_connection.py +index 51f1453dde7539c9348e6873820df285993906e8..e37d82a82a882c072cb938a90eb4486b51cdad99 100644 +--- a/h11/_connection.py ++++ b/h11/_connection.py +@@ -219,7 +219,7 @@ + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ +- return self._cstate.states.get(self.our_role, self._cstate.default_state) ++ return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: +@@ -536,10 +536,10 @@ + + """ + data_list = self.send_with_data_passthrough(event) +- if data_list is not None: ++ if data_list is None: + return None + else: +- return b"".join(reversed(data_list)) ++ return b"".join(data_list) + + def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: + """Identical to :meth:`send`, except that in situations where diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c81e04011ccd900f9c780079001725f627a1a233 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/solution/solve.sh @@ -0,0 +1,32 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_connection.py b/h11/_connection.py +index 51f1453dde7539c9348e6873820df285993906e8..e37d82a82a882c072cb938a90eb4486b51cdad99 100644 +--- a/h11/_connection.py ++++ b/h11/_connection.py +@@ -219,7 +219,7 @@ + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ +- return self._cstate.states.get(self.our_role, self._cstate.default_state) ++ return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: +@@ -536,10 +536,10 @@ + + """ + data_list = self.send_with_data_passthrough(event) +- if data_list is not None: ++ if data_list is None: + return None + else: +- return b"".join(reversed(data_list)) ++ return b"".join(data_list) + + def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: + """Identical to :meth:`send`, except that in situations where +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..3e22462c5a8e233db8eadc45ddbea0e291451c08 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..af1f9b204967135f317792f78912a4ad5b2cdd10 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_connection.py b/h11/_connection.py +index 51f1453dde7539c9348e6873820df285993906e8..e37d82a82a882c072cb938a90eb4486b51cdad99 100644 +--- a/h11/_connection.py ++++ b/h11/_connection.py +@@ -219,7 +219,7 @@ + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ +- return self._cstate.states.get(self.our_role, self._cstate.default_state) ++ return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__5ug1a88v/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..09d7cd73e14ba93cacbd44c1928d4f424f36e455 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "5392358b16399f3d9d707691397499b2461133676cfc8ae58a1564e4eb88db26", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "39730ba30398a44cf2670a2f792e5ad2b5d8eb4f786f49623e931ad48e6747cc", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "4e9c8d870dddba0ca900f3809ac7bc69d9408f699133d47dc7f0c6d17446e5d4", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "40b94111c76fc6ce152b300d68ba9892580a0f04", + "source_completion_sha256": "3dfcd707425c7e7a590d7ba47732259ab3b31bc84641c4212f31513478cac33a", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "4ae57a46dab60f4744ed04a254cd198a5b4cf2b959cfd2d3e51464ffb9b8a13b", + "is_fork": true, + "learner_path": "tasks/2b42ad6728cd6c9ceaa36799/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/40b94111c76fc6ce152b300d68ba9892580a0f04/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "67a61aeeb993403706aa61067bbe60841446325a97cc45d15c6d520804c001d4", + "provenance_path": "tasks/2b42ad6728cd6c9ceaa36799/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "40b94111c76fc6ce152b300d68ba9892580a0f04", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6381ab1f53308555c6d38276bdea23d63aa4ae58", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "task_sha256": "5691d2cc43cfc29eb73ac005fbae58503f3a793913f97c1d1d43d9a04b65c133", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48a034e967b8d91fd9c40945c2946d34575c457e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/instruction.md @@ -0,0 +1,41 @@ +Data event attributes swapped and reversed unexpectedly + +#### Description + +When creating Data events, the data appears to be reversed and the chunk_start/chunk_end attributes are swapped. This affects HTTP message body handling. + +#### Steps/Code to Reproduce + +```python +import h11 + +# Create a simple Data event +data_event = h11.Data(data=b'hello', chunk_start=True, chunk_end=False) + +print(f"Expected data: b'hello'") +print(f"Actual data: {data_event.data}") +print(f"Expected chunk_start: True, chunk_end: False") +print(f"Actual chunk_start: {data_event.chunk_start}, chunk_end: {data_event.chunk_end}") +``` + +Expected output: +``` +Expected data: b'hello' +Actual data: b'hello' +Expected chunk_start: True, chunk_end: False +Actual chunk_start: True, chunk_end: False +``` + +Actual output: +``` +Expected data: b'hello' +Actual data: b'olleh' +Expected chunk_start: True, chunk_end: False +Actual chunk_start: False, chunk_end: True +``` + +The data bytes are being reversed and the chunk boundary flags are swapped, which breaks HTTP message processing. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5ff8f9a70da0a437698941faa0c49143db3492bd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "6381ab1f53308555c6d38276bdea23d63aa4ae58", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "40b94111c76fc6ce152b300d68ba9892580a0f04" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_events.py", + "h11/tests/test_helpers.py", + "h11/tests/test_io.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": [ + "h11/_events.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 996013, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "4ae57a46dab60f4744ed04a254cd198a5b4cf2b959cfd2d3e51464ffb9b8a13b", + "is_fork": true, + "learner_path": "tasks/2b42ad6728cd6c9ceaa36799/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/40b94111c76fc6ce152b300d68ba9892580a0f04/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "67a61aeeb993403706aa61067bbe60841446325a97cc45d15c6d520804c001d4", + "provenance_path": "tasks/2b42ad6728cd6c9ceaa36799/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "40b94111c76fc6ce152b300d68ba9892580a0f04", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6381ab1f53308555c6d38276bdea23d63aa4ae58", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "task_sha256": "5691d2cc43cfc29eb73ac005fbae58503f3a793913f97c1d1d43d9a04b65c133", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..e58245a1f345c6a5b88b5296ae955977b57ffd85 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "5392358b16399f3d9d707691397499b2461133676cfc8ae58a1564e4eb88db26", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/40b94111c76fc6ce152b300d68ba9892580a0f04/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "3dfcd707425c7e7a590d7ba47732259ab3b31bc84641c4212f31513478cac33a", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "16535b1f8bb0e1020d79eec78faee27f04452381e60b1a24848490283cdc774a", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "4ae57a46dab60f4744ed04a254cd198a5b4cf2b959cfd2d3e51464ffb9b8a13b", + "is_fork": true, + "learner_path": "tasks/2b42ad6728cd6c9ceaa36799/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/40b94111c76fc6ce152b300d68ba9892580a0f04/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "67a61aeeb993403706aa61067bbe60841446325a97cc45d15c6d520804c001d4", + "provenance_path": "tasks/2b42ad6728cd6c9ceaa36799/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "40b94111c76fc6ce152b300d68ba9892580a0f04", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6381ab1f53308555c6d38276bdea23d63aa4ae58", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__84fosk9x", + "task_sha256": "5691d2cc43cfc29eb73ac005fbae58503f3a793913f97c1d1d43d9a04b65c133", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..536b9ad1df944e010ea37005044eb2a2a01cbaed --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/provided-gold.diff @@ -0,0 +1,26 @@ +diff --git a/h11/_events.py b/h11/_events.py +index f0df1f2da031d6c5e483ecd352c00ee1067c80c8..ca1c3adbde2c4e7710482a18e3471f91f1da610e 100644 +--- a/h11/_events.py ++++ b/h11/_events.py +@@ -299,9 +299,9 @@ + def __init__( + self, data: bytes, chunk_start: bool = False, chunk_end: bool = False + ) -> None: +- object.__setattr__(self, "data", data[::-1]) +- object.__setattr__(self, "chunk_start", chunk_end) +- object.__setattr__(self, "chunk_end", chunk_start) ++ object.__setattr__(self, "data", data) ++ object.__setattr__(self, "chunk_start", chunk_start) ++ object.__setattr__(self, "chunk_end", chunk_end) + + # This is an unhashable type. + __hash__ = None # type: ignore +@@ -346,7 +346,7 @@ + if headers is None: + headers = Headers([]) + elif not isinstance(headers, Headers): +- headers = normalize_and_validate(headers[::-1], _parsed=_parsed) ++ headers = normalize_and_validate(headers, _parsed=_parsed) + + object.__setattr__(self, "headers", headers) + diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6933acfbe5a92c85c83e24bf6ef41f83a700f352 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/solution/solve.sh @@ -0,0 +1,32 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_events.py b/h11/_events.py +index f0df1f2da031d6c5e483ecd352c00ee1067c80c8..ca1c3adbde2c4e7710482a18e3471f91f1da610e 100644 +--- a/h11/_events.py ++++ b/h11/_events.py +@@ -299,9 +299,9 @@ + def __init__( + self, data: bytes, chunk_start: bool = False, chunk_end: bool = False + ) -> None: +- object.__setattr__(self, "data", data[::-1]) +- object.__setattr__(self, "chunk_start", chunk_end) +- object.__setattr__(self, "chunk_end", chunk_start) ++ object.__setattr__(self, "data", data) ++ object.__setattr__(self, "chunk_start", chunk_start) ++ object.__setattr__(self, "chunk_end", chunk_end) + + # This is an unhashable type. + __hash__ = None # type: ignore +@@ -346,7 +346,7 @@ + if headers is None: + headers = Headers([]) + elif not isinstance(headers, Headers): +- headers = normalize_and_validate(headers[::-1], _parsed=_parsed) ++ headers = normalize_and_validate(headers, _parsed=_parsed) + + object.__setattr__(self, "headers", headers) + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..9aad2eb0b22f8eafb97c8f0eeed8f7ffd6923cbc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..a513fde1988bf21dd2a81a6ce1878977c4089b7c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/canaries/first-hunk-only.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_events.py b/h11/_events.py +index f0df1f2da031d6c5e483ecd352c00ee1067c80c8..ca1c3adbde2c4e7710482a18e3471f91f1da610e 100644 +--- a/h11/_events.py ++++ b/h11/_events.py +@@ -299,9 +299,9 @@ + def __init__( + self, data: bytes, chunk_start: bool = False, chunk_end: bool = False + ) -> None: +- object.__setattr__(self, "data", data[::-1]) +- object.__setattr__(self, "chunk_start", chunk_end) +- object.__setattr__(self, "chunk_end", chunk_start) ++ object.__setattr__(self, "data", data) ++ object.__setattr__(self, "chunk_start", chunk_start) ++ object.__setattr__(self, "chunk_end", chunk_end) + + # This is an unhashable type. + __hash__ = None # type: ignore +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__84fosk9x/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..582c226c9c66679a458443a900e9cd90efcf236b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "79e8a12a632095be8220c006cdd887fadb25a45dd2f9d1c2f76a8efa3eaa9f49", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "6455b11a446f72ceda0328a24ada9318e1adb96b5419fd0c6c1697f016cca767", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "214b13b7b98f4e02655a186c1d514f0e95071543d782c86a5a8c2410df972dcc", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "e733a21f4f1e4705a4c81a137b827c1fb05a5672", + "source_completion_sha256": "1530ad99e5ffca3d78c3613f71cb2c7d0083e416ae849e2290f58896a07e3766", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "73c1d11540ff55979ce17c40f993c871b92cfd0735edaa75191f2a5040a82ea9", + "is_fork": true, + "learner_path": "tasks/4d5bb555062edafb06fdb6bf/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/e733a21f4f1e4705a4c81a137b827c1fb05a5672/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "5e5fa0ef8b391d225e13e48cd226e8fa632689d70517f12f9b23e943148e0140", + "provenance_path": "tasks/4d5bb555062edafb06fdb6bf/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e733a21f4f1e4705a4c81a137b827c1fb05a5672", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2fec95ef1906e967b2a555d0cad7dacf518c1061", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "task_sha256": "d3768ec70562f6ade24a14bc8fe6b23bdc2fc718b24ddb7025284ef722b494cf", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3bf7d83fc6aae9d064cf5957c4cdd3577f0725f9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/instruction.md @@ -0,0 +1,41 @@ +Connection state machine broken after recent changes + +#### Description + +The HTTP connection state machine appears to be completely broken. Basic HTTP client/server interactions are failing with various errors including `AttributeError: 'tuple' object has no attribute 'discard'` and incorrect state transitions. + +#### Steps/Code to Reproduce + +```python +import h11 + +# Simple client connection fails +c = h11.Connection(h11.CLIENT) +c.send(h11.Request(method='GET', target='/', headers=[('Host', 'example.com')])) +c.send(h11.EndOfMessage()) + +# This should work but crashes +c.receive_data(b'HTTP/1.0 200 OK\r\n\r\n') +c.next_event() +``` + +Also fails with basic server usage: + +```python +import h11 + +c = h11.Connection(h11.SERVER) +c.receive_data(b'GET / HTTP/1.0\r\n\r\n') +events = [] +while True: + event = c.next_event() + if event is h11.NEED_DATA: + break + events.append(event) +``` + +The connection state logic seems fundamentally broken - connections that should be reusable aren't, keep-alive behavior is inverted, and protocol switching logic is completely wrong. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..f60dfa95122aa928b8007ba0283b5ab86c15dcd6 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "2fec95ef1906e967b2a555d0cad7dacf518c1061", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "e733a21f4f1e4705a4c81a137b827c1fb05a5672" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_io.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_state.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": [ + "h11/_state.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1008216, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "73c1d11540ff55979ce17c40f993c871b92cfd0735edaa75191f2a5040a82ea9", + "is_fork": true, + "learner_path": "tasks/4d5bb555062edafb06fdb6bf/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/e733a21f4f1e4705a4c81a137b827c1fb05a5672/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "5e5fa0ef8b391d225e13e48cd226e8fa632689d70517f12f9b23e943148e0140", + "provenance_path": "tasks/4d5bb555062edafb06fdb6bf/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e733a21f4f1e4705a4c81a137b827c1fb05a5672", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2fec95ef1906e967b2a555d0cad7dacf518c1061", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "task_sha256": "d3768ec70562f6ade24a14bc8fe6b23bdc2fc718b24ddb7025284ef722b494cf", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..46ae2bef7da576d88d57914f0c0677ecc95ff8d6 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "79e8a12a632095be8220c006cdd887fadb25a45dd2f9d1c2f76a8efa3eaa9f49", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/e733a21f4f1e4705a4c81a137b827c1fb05a5672/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "1530ad99e5ffca3d78c3613f71cb2c7d0083e416ae849e2290f58896a07e3766", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "992669dec90d0c9f575cb5181a6b53c9aadaf3dc73b1cb58bf2ed24b45b15749", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "73c1d11540ff55979ce17c40f993c871b92cfd0735edaa75191f2a5040a82ea9", + "is_fork": true, + "learner_path": "tasks/4d5bb555062edafb06fdb6bf/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/e733a21f4f1e4705a4c81a137b827c1fb05a5672/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "5e5fa0ef8b391d225e13e48cd226e8fa632689d70517f12f9b23e943148e0140", + "provenance_path": "tasks/4d5bb555062edafb06fdb6bf/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e733a21f4f1e4705a4c81a137b827c1fb05a5672", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2fec95ef1906e967b2a555d0cad7dacf518c1061", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__9wljotoa", + "task_sha256": "d3768ec70562f6ade24a14bc8fe6b23bdc2fc718b24ddb7025284ef722b494cf", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..cf3243cb83cb7de0dbcca97bd633783d7fd9ec2b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/provided-gold.diff @@ -0,0 +1,58 @@ +diff --git a/h11/_state.py b/h11/_state.py +index a881fce558d81308d920ec0ade2926e2a06c8a7a..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 100644 +--- a/h11/_state.py ++++ b/h11/_state.py +@@ -265,7 +265,7 @@ + self._fire_state_triggered_transitions() + + def process_keep_alive_disabled(self) -> None: +- self.keep_alive = True ++ self.keep_alive = False + self._fire_state_triggered_transitions() + + def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: +@@ -281,19 +281,19 @@ + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER +- if server_switch_event in self.pending_switch_proposals: ++ if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( +- "Received server _SWITCH_UPGRADE event with a pending proposal" ++ "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) +- if server_switch_event is None and event_type is Response: +- self.pending_switch_proposals = list() ++ if server_switch_event is None and _event_type is Response: ++ self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) +- # Special case: the server state does get to see Response ++ # Special case: the server state does get to see Request + # events. +- if _event_type is Response: +- assert role is SERVER +- self._fire_event_triggered_transitions(CLIENT, (Request, SERVER)) ++ if _event_type is Request: ++ assert role is CLIENT ++ self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( +@@ -354,10 +354,12 @@ + return + + def start_next_cycle(self) -> None: +- if self.states != {CLIENT: IDLE, SERVER: IDLE}: ++ if self.states != {CLIENT: DONE, SERVER: DONE}: + raise LocalProtocolError( + f"not in a reusable state. self.states={self.states}" + ) +- assert not self.keep_alive +- assert self.pending_switch_proposals +- self.states = {CLIENT: DONE, SERVER: IDLE} ++ # Can't reach DONE/DONE with any of these active, but still, let's be ++ # sure. ++ assert self.keep_alive ++ assert not self.pending_switch_proposals ++ self.states = {CLIENT: IDLE, SERVER: IDLE} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a40b201fef5fe57c2810099a192859f1c6d3b475 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/solution/solve.sh @@ -0,0 +1,64 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_state.py b/h11/_state.py +index a881fce558d81308d920ec0ade2926e2a06c8a7a..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 100644 +--- a/h11/_state.py ++++ b/h11/_state.py +@@ -265,7 +265,7 @@ + self._fire_state_triggered_transitions() + + def process_keep_alive_disabled(self) -> None: +- self.keep_alive = True ++ self.keep_alive = False + self._fire_state_triggered_transitions() + + def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: +@@ -281,19 +281,19 @@ + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER +- if server_switch_event in self.pending_switch_proposals: ++ if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( +- "Received server _SWITCH_UPGRADE event with a pending proposal" ++ "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) +- if server_switch_event is None and event_type is Response: +- self.pending_switch_proposals = list() ++ if server_switch_event is None and _event_type is Response: ++ self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) +- # Special case: the server state does get to see Response ++ # Special case: the server state does get to see Request + # events. +- if _event_type is Response: +- assert role is SERVER +- self._fire_event_triggered_transitions(CLIENT, (Request, SERVER)) ++ if _event_type is Request: ++ assert role is CLIENT ++ self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( +@@ -354,10 +354,12 @@ + return + + def start_next_cycle(self) -> None: +- if self.states != {CLIENT: IDLE, SERVER: IDLE}: ++ if self.states != {CLIENT: DONE, SERVER: DONE}: + raise LocalProtocolError( + f"not in a reusable state. self.states={self.states}" + ) +- assert not self.keep_alive +- assert self.pending_switch_proposals +- self.states = {CLIENT: DONE, SERVER: IDLE} ++ # Can't reach DONE/DONE with any of these active, but still, let's be ++ # sure. ++ assert self.keep_alive ++ assert not self.pending_switch_proposals ++ self.states = {CLIENT: IDLE, SERVER: IDLE} +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..641f291772229283b73a81ec648c3d8b15269cfb --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..e42a95d681014395395654a3ef3fe4c028a54a07 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_state.py b/h11/_state.py +index a881fce558d81308d920ec0ade2926e2a06c8a7a..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 100644 +--- a/h11/_state.py ++++ b/h11/_state.py +@@ -265,7 +265,7 @@ + self._fire_state_triggered_transitions() + + def process_keep_alive_disabled(self) -> None: +- self.keep_alive = True ++ self.keep_alive = False + self._fire_state_triggered_transitions() + + def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__9wljotoa/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..358e101d28611254ab9483c4ed33e41ae33d2369 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "2f1ddcb1daaf6903ff95c427901d1ce6775e9824e7941fd2d55a72f6767f259f", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "6802a1ffeb2b200c129d47cad9d16655398bda532bfa1f124c7377515f58e1cc", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "f19e2130ff839cfe9d417249dda73fda9d043545858350132ea150539ee979ce", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "a159e225b005e470094a9fcb1cb2d3043ffa48e0", + "source_completion_sha256": "1b2817f33650197b439e59e6adc1fe0ba927161ea14ff70141f73f4b8f2d3155", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "46d1464bf1242c5dd357d8857f3625e82a5049b081a5be814f71cf920cbdb6b3", + "is_fork": true, + "learner_path": "tasks/d00f2d4ee74bc6d761a3eca8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a159e225b005e470094a9fcb1cb2d3043ffa48e0/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "fdc82a36a0b256e9aee97b1785b5ae7d054094658e3213928747b7160674de55", + "provenance_path": "tasks/d00f2d4ee74bc6d761a3eca8/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a159e225b005e470094a9fcb1cb2d3043ffa48e0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "75b3452ae5183aae1ca7b379005f900ae98708ea", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "task_sha256": "ae13b2501ecbf710b6e45007a6a8141f94337e0ef33a0f8d47dac6896ba620a7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a058391b89131c38f69f0f1d21498bae4b875680 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/instruction.md @@ -0,0 +1,52 @@ +HTTP/1.1 protocol writers producing incorrect output + +#### Description + +The HTTP/1.1 protocol writers are generating malformed output that breaks standard HTTP communication. When sending responses with content-length or chunked encoding, the writers are producing incorrect protocol messages. + +#### Steps/Code to Reproduce + +```python +import h11 + +# Test chunked encoding +c = h11.Connection(h11.SERVER) +c.receive_data(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n') +c.next_event() # Request +c.next_event() # EndOfMessage + +response = h11.Response(status_code=200, headers=[]) +data = h11.Data(data=b'hello') +eom = h11.EndOfMessage() + +print("Response:", repr(c.send(response))) +print("Data:", repr(c.send(data))) +print("EOM:", repr(c.send(eom))) +``` + +Expected chunked response should end with `0\r\n\r\n` but getting `1\r\n` instead. + +```python +# Test content-length with zero bytes +c = h11.Connection(h11.SERVER) +c.receive_data(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n') +c.next_event() # Request +c.next_event() # EndOfMessage + +response = h11.Response(status_code=204, headers=[('Content-Length', '0')]) +eom = h11.EndOfMessage() + +print("Response:", repr(c.send(response))) +try: + print("EOM:", repr(c.send(eom))) +except Exception as e: + print("Error:", e) +``` + +This should work fine for zero-length content but throws "Too little data for declared Content-Length" error. + +The protocol writers seem to have inverted logic conditions causing them to fail on valid HTTP scenarios and potentially accept invalid ones. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..dbc17038d9fe8b5b0c21c61e3123b9e1d8c88c70 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "75b3452ae5183aae1ca7b379005f900ae98708ea", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "a159e225b005e470094a9fcb1cb2d3043ffa48e0" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_io.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": [ + "h11/_writers.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1001202, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "46d1464bf1242c5dd357d8857f3625e82a5049b081a5be814f71cf920cbdb6b3", + "is_fork": true, + "learner_path": "tasks/d00f2d4ee74bc6d761a3eca8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a159e225b005e470094a9fcb1cb2d3043ffa48e0/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "fdc82a36a0b256e9aee97b1785b5ae7d054094658e3213928747b7160674de55", + "provenance_path": "tasks/d00f2d4ee74bc6d761a3eca8/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a159e225b005e470094a9fcb1cb2d3043ffa48e0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "75b3452ae5183aae1ca7b379005f900ae98708ea", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "task_sha256": "ae13b2501ecbf710b6e45007a6a8141f94337e0ef33a0f8d47dac6896ba620a7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..7a94f42620b7468ccb1c86ac3609fb1bf0dcca25 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "2f1ddcb1daaf6903ff95c427901d1ce6775e9824e7941fd2d55a72f6767f259f", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a159e225b005e470094a9fcb1cb2d3043ffa48e0/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "1b2817f33650197b439e59e6adc1fe0ba927161ea14ff70141f73f4b8f2d3155", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "bafeb2396d30ba13c385b1ef0ccbe8d333cc1e8d71980a882333d2120b68e115", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "46d1464bf1242c5dd357d8857f3625e82a5049b081a5be814f71cf920cbdb6b3", + "is_fork": true, + "learner_path": "tasks/d00f2d4ee74bc6d761a3eca8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/a159e225b005e470094a9fcb1cb2d3043ffa48e0/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "fdc82a36a0b256e9aee97b1785b5ae7d054094658e3213928747b7160674de55", + "provenance_path": "tasks/d00f2d4ee74bc6d761a3eca8/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a159e225b005e470094a9fcb1cb2d3043ffa48e0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "75b3452ae5183aae1ca7b379005f900ae98708ea", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__adjip79b", + "task_sha256": "ae13b2501ecbf710b6e45007a6a8141f94337e0ef33a0f8d47dac6896ba620a7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..356d23124dfe02a2f4f64596d01a60d518c6e64f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/provided-gold.diff @@ -0,0 +1,37 @@ +diff --git a/h11/_writers.py b/h11/_writers.py +index bd5d6335a7434bf1f095c13f3f0268325dff6d71..939cdb912a9debaea07fbf3a9ac04549c44d077c 100644 +--- a/h11/_writers.py ++++ b/h11/_writers.py +@@ -92,9 +92,9 @@ + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: +- if self._length == 0: ++ if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") +- if not headers: ++ if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + +@@ -109,8 +109,8 @@ + write(b"\r\n") + + def send_eom(self, headers: Headers, write: Writer) -> None: ++ write(b"0\r\n") + write_headers(headers, write) +- write(b"1\r\n") + + + class Http10Writer(BodyWriter): +@@ -118,8 +118,8 @@ + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: +- if not headers: +- raise LocalProtocolError("can't send trailers to HTTP/1.1 client") ++ if headers: ++ raise LocalProtocolError("can't send trailers to HTTP/1.0 client") + # no need to close the socket ourselves, that will be taken care of by + # Connection: close machinery + diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..cdf5fabba8fec373085ad419c6a080039debeec2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/solution/solve.sh @@ -0,0 +1,43 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_writers.py b/h11/_writers.py +index bd5d6335a7434bf1f095c13f3f0268325dff6d71..939cdb912a9debaea07fbf3a9ac04549c44d077c 100644 +--- a/h11/_writers.py ++++ b/h11/_writers.py +@@ -92,9 +92,9 @@ + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: +- if self._length == 0: ++ if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") +- if not headers: ++ if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + +@@ -109,8 +109,8 @@ + write(b"\r\n") + + def send_eom(self, headers: Headers, write: Writer) -> None: ++ write(b"0\r\n") + write_headers(headers, write) +- write(b"1\r\n") + + + class Http10Writer(BodyWriter): +@@ -118,8 +118,8 @@ + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: +- if not headers: +- raise LocalProtocolError("can't send trailers to HTTP/1.1 client") ++ if headers: ++ raise LocalProtocolError("can't send trailers to HTTP/1.0 client") + # no need to close the socket ourselves, that will be taken care of by + # Connection: close machinery + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..695f87079503382833cd8975024ee82adcef3668 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "pass-to-pass": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..dadbf1f3cb266a10fc6bd953611d9ca02a2f9748 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/canaries/first-hunk-only.sh @@ -0,0 +1,22 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_writers.py b/h11/_writers.py +index bd5d6335a7434bf1f095c13f3f0268325dff6d71..939cdb912a9debaea07fbf3a9ac04549c44d077c 100644 +--- a/h11/_writers.py ++++ b/h11/_writers.py +@@ -92,9 +92,9 @@ + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: +- if self._length == 0: ++ if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") +- if not headers: ++ if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__adjip79b/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..6b3b20c21f96c275c1f8c30d5a6bffdf8f89a7a7 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "6958ecfa7e315edd1fa49db0179a37c0d39bd569fc66fc1f0ce642cd4d139385", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "bdabff9df06233c660f423f35a92bd4cec03c86657c184313b5fa77e8c097a68", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "eff48a8e3dbaa9842bb03b1fb94093bf15a527e3c516271bf10b4fdc5a0ad3b1", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf", + "source_completion_sha256": "4ca002742a7dd3b592baa5c4db04279dcabbfeb9643b8a9df0dfd1c822f7ddc1", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "7ad95411b055761c93eeb33c3a750135a221089cb21963021400b5d2c942d898", + "is_fork": true, + "learner_path": "tasks/7afa679494104bb357d46b9f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "3e3a346fc0fe9b668ad3258b51ea56a03709473aa5553ab2b041fe2602437073", + "provenance_path": "tasks/7afa679494104bb357d46b9f/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6edf8bccb8eeec8813e69267b13392711a989148", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "task_sha256": "9a3217fa3c12d7467f980904fd43d7c7f2d8afb03b728bf11c024781720be9ac", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8cfe0d15bda1859d5a669b64397af9d2676aff72 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/instruction.md @@ -0,0 +1,34 @@ +# InformationalResponse status code range is incorrect + +## Description + +I found an issue with the status code validation in the `InformationalResponse` class. The current implementation doesn't allow for status code 100 to be used, which is a valid informational response code. + +## Steps to reproduce + +```python +from h11 import InformationalResponse + +# This should work but raises an error +response = InformationalResponse(status_code=100, headers=[]) +``` + +When trying to create an `InformationalResponse` with status code 100, it raises a `LocalProtocolError` with the message: +"InformationalResponse status_code should be in range [100, 200), not 100" + +## Expected behavior + +Status code 100 should be accepted as a valid informational response code. The range check should be inclusive for the lower bound (100). + +Additionally, there seems to be an issue with the `Response` class where it's accepting status codes in the 100-199 range, which should be exclusive to `InformationalResponse`. + +## Actual behavior + +- `InformationalResponse` rejects status code 100, which should be valid +- `Response` accepts status codes in the 100-199 range, which should be invalid for this class + +This is causing problems when trying to send a "100 Continue" response, which is a common HTTP pattern. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..cb31375bd00d6de1b7f7c693ad3a28383290a7b6 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_events.py::test_events" + ], + "PASS_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "6edf8bccb8eeec8813e69267b13392711a989148", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_against_stdlib_http.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_io.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_connection.py", + "h11/tests/test_events.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": [ + "h11/_events.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1016765, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "7ad95411b055761c93eeb33c3a750135a221089cb21963021400b5d2c942d898", + "is_fork": true, + "learner_path": "tasks/7afa679494104bb357d46b9f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "3e3a346fc0fe9b668ad3258b51ea56a03709473aa5553ab2b041fe2602437073", + "provenance_path": "tasks/7afa679494104bb357d46b9f/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6edf8bccb8eeec8813e69267b13392711a989148", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "task_sha256": "9a3217fa3c12d7467f980904fd43d7c7f2d8afb03b728bf11c024781720be9ac", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/provenance.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..0082b955df3ba7b1c2a39e14d4ae7ca508795452 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "6958ecfa7e315edd1fa49db0179a37c0d39bd569fc66fc1f0ce642cd4d139385", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf/LICENSE.txt" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "4ca002742a7dd3b592baa5c4db04279dcabbfeb9643b8a9df0dfd1c822f7ddc1", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "5648d09f97fdf57f133199136e28693962c9985da1df0d5d4531bfef3608c436", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "7ad95411b055761c93eeb33c3a750135a221089cb21963021400b5d2c942d898", + "is_fork": true, + "learner_path": "tasks/7afa679494104bb357d46b9f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "3e3a346fc0fe9b668ad3258b51ea56a03709473aa5553ab2b041fe2602437073", + "provenance_path": "tasks/7afa679494104bb357d46b9f/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "186e1905f0e2dd4e00aa7b3ef3bc7fa614157aaf", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6edf8bccb8eeec8813e69267b13392711a989148", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__btwmyz5k", + "task_sha256": "9a3217fa3c12d7467f980904fd43d7c7f2d8afb03b728bf11c024781720be9ac", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "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": "3c1e43a05ef79d1440896d352c6a6e1959162f0fe08c40870c7e2643a2b04a7b" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/provided-gold.diff b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a7f7b306231bc5df6d628e5b6eadaec6b2c9c543 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/provided-gold.diff @@ -0,0 +1,22 @@ +diff --git a/h11/_events.py b/h11/_events.py +index c845781c9b3ab53d9e290e64d5ff7a7c3c0aad3f..ca1c3adbde2c4e7710482a18e3471f91f1da610e 100644 +--- a/h11/_events.py ++++ b/h11/_events.py +@@ -204,7 +204,7 @@ + """ + + def __post_init__(self) -> None: +- if not (100 < self.status_code <= 200): ++ if not (100 <= self.status_code < 200): + raise LocalProtocolError( + "InformationalResponse status_code should be in range " + "[100, 200), not {}".format(self.status_code) +@@ -245,7 +245,7 @@ + """ + + def __post_init__(self) -> None: +- if not (100 <= self.status_code < 1000): ++ if not (200 <= self.status_code < 1000): + raise LocalProtocolError( + "Response status_code should be in range [200, 1000), not {}".format( + self.status_code diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/solution/solve.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4452def4918768d83b17988d577f46424826781a --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/h11/_events.py b/h11/_events.py +index c845781c9b3ab53d9e290e64d5ff7a7c3c0aad3f..ca1c3adbde2c4e7710482a18e3471f91f1da610e 100644 +--- a/h11/_events.py ++++ b/h11/_events.py +@@ -204,7 +204,7 @@ + """ + + def __post_init__(self) -> None: +- if not (100 < self.status_code <= 200): ++ if not (100 <= self.status_code < 200): + raise LocalProtocolError( + "InformationalResponse status_code should be in range " + "[100, 200), not {}".format(self.status_code) +@@ -245,7 +245,7 @@ + """ + + def __post_init__(self) -> None: +- if not (100 <= self.status_code < 1000): ++ if not (200 <= self.status_code < 1000): + raise LocalProtocolError( + "Response status_code should be in range [200, 1000), not {}".format( + self.status_code +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/task.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09d73972206f4abd51e0b1925e13af418cb56561 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/task.toml @@ -0,0 +1,23 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/check_pytest.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), 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 capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case 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, target) for case in cases) for target 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") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/expected-panels.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..1793474577890d70c4832a7f13eaedac4874e32a --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/expected-panels.json @@ -0,0 +1,82 @@ +{ + "fail-to-pass": [ + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_events.py::test_events" + ], + "pass-to-pass": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ] +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/grade.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/panel-config.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..85128b4e445ba6a4d35a7725b5514e676691d904 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/panel-config.json @@ -0,0 +1,28 @@ +{ + "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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/test.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted-inventory.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaf29c6be630201adf01f8a7d320d9aab0da43c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted-inventory.json @@ -0,0 +1,82 @@ +{ + "directory_roots": [ + "h11/tests" + ], + "files": { + "h11/tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "h11/tests/data/test-file": { + "bytes": 65, + "mode": 420, + "sha256": "649d3746ab3df28270dbd387cc983b2e5333c8641a440634af702a05e336c155" + }, + "h11/tests/helpers.py": { + "bytes": 3355, + "mode": 420, + "sha256": "6b51151bfa7bc54e3046c6b7b4c3d3471b9a2829ab7ada24f6cc575afa9f9900" + }, + "h11/tests/test_against_stdlib_http.py": { + "bytes": 3966, + "mode": 420, + "sha256": "7850fb255d4481f92f573efddd9cc9585d678514cb57a5e73e3199b21f69f55a" + }, + "h11/tests/test_connection.py": { + "bytes": 38149, + "mode": 420, + "sha256": "4c7f829daa7070330c739a36eeaba404ddf251fe04638cfb3a74c2b017093615" + }, + "h11/tests/test_events.py": { + "bytes": 4545, + "mode": 420, + "sha256": "117550bbcb266626fe2482d04388f62869adeef6c92aa29231fca78024c9011e" + }, + "h11/tests/test_headers.py": { + "bytes": 5612, + "mode": 420, + "sha256": "a9df13d597a7bb3e466c3eb0925489e46f154bbb6bad880c5748d3f9232faa0f" + }, + "h11/tests/test_helpers.py": { + "bytes": 652, + "mode": 420, + "sha256": "7fd9082bcb4815b7b54e197d6f4f7a8b3f242786a1142fe00714a0c3322c854d" + }, + "h11/tests/test_io.py": { + "bytes": 16158, + "mode": 420, + "sha256": "841cd5d40669a78f08108a9060824bc8f5e00e007d451f5bc53767e856cd9285" + }, + "h11/tests/test_receivebuffer.py": { + "bytes": 3454, + "mode": 420, + "sha256": "de319b789337e8092a83fa4084f6fb5f3227d8d4ba4613e0f91ca0f04bbacad9" + }, + "h11/tests/test_state.py": { + "bytes": 8928, + "mode": 420, + "sha256": "aea965f56a85b093c4d334abb429fd2c7eb9f663cab0379767e0f05f095eb814" + }, + "h11/tests/test_util.py": { + "bytes": 2970, + "mode": 420, + "sha256": "54ee4be274857b8a60b52c0abafeaeffa9741fb51e8b317958ab874d6ade83bd" + }, + "pyproject.toml": { + "bytes": 1133, + "mode": 420, + "sha256": "ddb684a564184056b10737f3c40fa1d8ede7d654785e5a665ad9aa9106455bc0" + }, + "setup.py": { + "bytes": 1277, + "mode": 420, + "sha256": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b" + }, + "tox.ini": { + "bytes": 660, + "mode": 420, + "sha256": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/__init__.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/data/test-file b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/data/test-file new file mode 100644 index 0000000000000000000000000000000000000000..d0be0a6c5d6c19a35f0e815b83e27f8d833ea88b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/data/test-file @@ -0,0 +1 @@ +92b12bc045050b55b848d37167a1a63947c364579889ce1d39788e45e9fac9e5 diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..571be44461b0847c9edb8654c9d528abed0b7800 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/helpers.py @@ -0,0 +1,101 @@ +from typing import cast, List, Type, Union, ValuesView + +from .._connection import Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import CLIENT, CLOSED, DONE, MUST_CLOSE, SERVER +from .._util import Sentinel + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + + +def get_all_events(conn: Connection) -> List[Event]: + got_events = [] + while True: + event = conn.next_event() + if event in (NEED_DATA, PAUSED): + break + event = cast(Event, event) + got_events.append(event) + if type(event) is ConnectionClosed: + break + return got_events + + +def receive_and_get(conn: Connection, data: bytes) -> List[Event]: + conn.receive_data(data) + return get_all_events(conn) + + +# Merges adjacent Data events, converts payloads to bytestrings, and removes +# chunk boundaries. +def normalize_data_events(in_events: List[Event]) -> List[Event]: + out_events: List[Event] = [] + for event in in_events: + if type(event) is Data: + event = Data(data=bytes(event.data), chunk_start=False, chunk_end=False) + if out_events and type(out_events[-1]) is type(event) is Data: + out_events[-1] = Data( + data=out_events[-1].data + event.data, + chunk_start=out_events[-1].chunk_start, + chunk_end=out_events[-1].chunk_end, + ) + else: + out_events.append(event) + return out_events + + +# Given that we want to write tests that push some events through a Connection +# and check that its state updates appropriately... we might as make a habit +# of pushing them through two Connections with a fake network link in +# between. +class ConnectionPair: + def __init__(self) -> None: + self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)} + self.other = {CLIENT: SERVER, SERVER: CLIENT} + + @property + def conns(self) -> ValuesView[Connection]: + return self.conn.values() + + # expect="match" if expect=send_events; expect=[...] to say what expected + def send( + self, + role: Type[Sentinel], + send_events: Union[List[Event], Event], + expect: Union[List[Event], Event, Literal["match"]] = "match", + ) -> bytes: + if not isinstance(send_events, list): + send_events = [send_events] + data = b"" + closed = False + for send_event in send_events: + new_data = self.conn[role].send(send_event) + if new_data is None: + closed = True + else: + data += new_data + # send uses b"" to mean b"", and None to mean closed + # receive uses b"" to mean closed, and None to mean "try again" + # so we have to translate between the two conventions + if data: + self.conn[self.other[role]].receive_data(data) + if closed: + self.conn[self.other[role]].receive_data(b"") + got_events = get_all_events(self.conn[self.other[role]]) + if expect == "match": + expect = send_events + if not isinstance(expect, list): + expect = [expect] + assert got_events == expect + return data diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_against_stdlib_http.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_against_stdlib_http.py new file mode 100644 index 0000000000000000000000000000000000000000..3f66a103c662bd0bcdacb94bf722b550bbe6c86c --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_against_stdlib_http.py @@ -0,0 +1,115 @@ +import json +import os.path +import socket +import socketserver +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler +from typing import Callable, Generator +from urllib.request import urlopen + +import h11 + + +@contextmanager +def socket_server( + handler: Callable[..., socketserver.BaseRequestHandler], +) -> Generator[socketserver.TCPServer, None, None]: + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) + thread = threading.Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01} + ) + thread.daemon = True + try: + thread.start() + yield httpd + finally: + httpd.shutdown() + + +test_file_path = os.path.join(os.path.dirname(__file__), "data/test-file") +with open(test_file_path, "rb") as f: + test_file_data = f.read() + + +class SingleMindedRequestHandler(SimpleHTTPRequestHandler): + def translate_path(self, path: str) -> str: + return test_file_path + + +def test_h11_as_client() -> None: + with socket_server(SingleMindedRequestHandler) as httpd: + with closing(socket.create_connection(httpd.server_address)) as s: # type: ignore[arg-type] + c = h11.Connection(h11.CLIENT) + + s.sendall( + c.send( + h11.Request( + method="GET", target="/foo", headers=[("Host", "localhost")] + ) + ) + ) + s.sendall(c.send(h11.EndOfMessage())) + + data = bytearray() + while True: + event = c.next_event() + print(event) + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Response: + assert event.status_code == 200 + if type(event) is h11.Data: + data += event.data + if type(event) is h11.EndOfMessage: + break + assert bytes(data) == test_file_data + + +class H11RequestHandler(socketserver.BaseRequestHandler): + def handle(self) -> None: + with closing(self.request) as s: + c = h11.Connection(h11.SERVER) + request = None + while True: + event = c.next_event() + if event is h11.NEED_DATA: + # Use a small read buffer to make things more challenging + # and exercise more paths :-) + c.receive_data(s.recv(10)) + continue + if type(event) is h11.Request: + request = event + if type(event) is h11.EndOfMessage: + break + assert request is not None + info = json.dumps( + { + "method": request.method.decode("ascii"), + "target": request.target.decode("ascii"), + "headers": { + name.decode("ascii"): value.decode("ascii") + for (name, value) in request.headers + }, + } + ) + s.sendall(c.send(h11.Response(status_code=200, headers=[]))) + s.sendall(c.send(h11.Data(data=info.encode("ascii")))) + s.sendall(c.send(h11.EndOfMessage())) + + +def test_h11_as_server() -> None: + with socket_server(H11RequestHandler) as httpd: + host, port = httpd.server_address + url = f"http://{host}:{port}/some-path" # type: ignore[str-bytes-safe] + with closing(urlopen(url)) as f: + assert f.getcode() == 200 + data = f.read() + info = json.loads(data.decode("ascii")) + print(info) + assert info["method"] == "GET" + assert info["target"] == "/some-path" + assert "urllib" in info["headers"]["user-agent"] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_connection.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..01260dcae3e6545db213d76eb664f5c7b8b168ca --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_connection.py @@ -0,0 +1,1120 @@ +from typing import Any, cast, Dict, List, Optional, Tuple, Type + +import pytest + +from .._connection import _body_framing, _keep_alive, Connection, NEED_DATA, PAUSED +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError, RemoteProtocolError, Sentinel +from .helpers import ConnectionPair, get_all_events, receive_and_get + + +def test__keep_alive() -> None: + assert _keep_alive( + Request(method="GET", target="/", headers=[("Host", "Example.com")]) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "close")], + ) + ) + assert not _keep_alive( + Request( + method="GET", + target="/", + headers=[("Host", "Example.com"), ("Connection", "a, b, cLOse, foo")], + ) + ) + assert not _keep_alive( + Request(method="GET", target="/", headers=[], http_version="1.0") + ) + + assert _keep_alive(Response(status_code=200, headers=[])) + assert not _keep_alive(Response(status_code=200, headers=[("Connection", "close")])) + assert not _keep_alive( + Response(status_code=200, headers=[("Connection", "a, b, cLOse, foo")]) + ) + assert not _keep_alive(Response(status_code=200, headers=[], http_version="1.0")) + + +def test__body_framing() -> None: + def headers(cl: Optional[int], te: bool) -> List[Tuple[str, str]]: + headers = [] + if cl is not None: + headers.append(("Content-Length", str(cl))) + if te: + headers.append(("Transfer-Encoding", "chunked")) + return headers + + def resp( + status_code: int = 200, cl: Optional[int] = None, te: bool = False + ) -> Response: + return Response(status_code=status_code, headers=headers(cl, te)) + + def req(cl: Optional[int] = None, te: bool = False) -> Request: + h = headers(cl, te) + h += [("Host", "example.com")] + return Request(method="GET", target="/", headers=h) + + # Special cases where the headers are ignored: + for kwargs in [{}, {"cl": 100}, {"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [ + (b"HEAD", resp(**kwargs)), + (b"GET", resp(status_code=204, **kwargs)), + (b"GET", resp(status_code=304, **kwargs)), + ]: + assert _body_framing(meth, r) == ("content-length", (0,)) + + # Transfer-encoding + for kwargs in [{"te": True}, {"cl": 100, "te": True}]: + kwargs = cast(Dict[str, Any], kwargs) + for meth, r in [(None, req(**kwargs)), (b"GET", resp(**kwargs))]: # type: ignore + assert _body_framing(meth, r) == ("chunked", ()) + + # Content-Length + for meth, r in [(None, req(cl=100)), (b"GET", resp(cl=100))]: # type: ignore + assert _body_framing(meth, r) == ("content-length", (100,)) + + # No headers + assert _body_framing(None, req()) == ("content-length", (0,)) # type: ignore + assert _body_framing(b"GET", resp()) == ("http/1.0", ()) + + +def test_Connection_basics_and_content_length() -> None: + with pytest.raises(ValueError): + Connection("CLIENT") # type: ignore + + p = ConnectionPair() + assert p.conn[CLIENT].our_role is CLIENT + assert p.conn[CLIENT].their_role is SERVER + assert p.conn[SERVER].our_role is SERVER + assert p.conn[SERVER].their_role is CLIENT + + data = p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Content-Length", "10")], + ), + ) + assert data == ( + b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 10\r\n\r\n" + ) + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + assert p.conn[CLIENT].our_state is SEND_BODY + assert p.conn[CLIENT].their_state is SEND_RESPONSE + assert p.conn[SERVER].our_state is SEND_RESPONSE + assert p.conn[SERVER].their_state is SEND_BODY + + assert p.conn[CLIENT].their_http_version is None + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + assert data == b"HTTP/1.1 100 \r\n\r\n" + + data = p.send(SERVER, Response(status_code=200, headers=[("Content-Length", "11")])) + assert data == b"HTTP/1.1 200 \r\nContent-Length: 11\r\n\r\n" + + for conn in p.conns: + assert conn.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + assert p.conn[CLIENT].their_http_version == b"1.1" + assert p.conn[SERVER].their_http_version == b"1.1" + + data = p.send(CLIENT, Data(data=b"12345")) + assert data == b"12345" + data = p.send( + CLIENT, Data(data=b"67890"), expect=[Data(data=b"67890"), EndOfMessage()] + ) + assert data == b"67890" + data = p.send(CLIENT, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + + data = p.send(SERVER, Data(data=b"1234567890")) + assert data == b"1234567890" + data = p.send(SERVER, Data(data=b"1"), expect=[Data(data=b"1"), EndOfMessage()]) + assert data == b"1" + data = p.send(SERVER, EndOfMessage(), expect=[]) + assert data == b"" + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunked() -> None: + p = ConnectionPair() + + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ), + ) + data = p.send(CLIENT, Data(data=b"1234567890", chunk_start=True, chunk_end=True)) + assert data == b"a\r\n1234567890\r\n" + data = p.send(CLIENT, Data(data=b"abcde", chunk_start=True, chunk_end=True)) + assert data == b"5\r\nabcde\r\n" + data = p.send(CLIENT, Data(data=b""), expect=[]) + assert data == b"" + data = p.send(CLIENT, EndOfMessage(headers=[("hello", "there")])) + assert data == b"0\r\nhello: there\r\n\r\n" + + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + p.send(SERVER, Data(data=b"54321", chunk_start=True, chunk_end=True)) + p.send(SERVER, Data(data=b"12345", chunk_start=True, chunk_end=True)) + p.send(SERVER, EndOfMessage()) + + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + + +def test_chunk_boundaries() -> None: + conn = Connection(our_role=SERVER) + + request = ( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n" + b"\r\n" + ) + conn.receive_data(request) + assert conn.next_event() == Request( + method="POST", + target="/", + headers=[("Host", "example.com"), ("Transfer-Encoding", "chunked")], + ) + assert conn.next_event() is NEED_DATA + + conn.receive_data(b"5\r\nhello\r\n") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"5\r\nhel") + assert conn.next_event() == Data(data=b"hel", chunk_start=True, chunk_end=False) + + conn.receive_data(b"l") + assert conn.next_event() == Data(data=b"l", chunk_start=False, chunk_end=False) + + conn.receive_data(b"o\r\n") + assert conn.next_event() == Data(data=b"o", chunk_start=False, chunk_end=True) + + conn.receive_data(b"5\r\nhello") + assert conn.next_event() == Data(data=b"hello", chunk_start=True, chunk_end=True) + + conn.receive_data(b"\r\n") + assert conn.next_event() == NEED_DATA + + conn.receive_data(b"0\r\n\r\n") + assert conn.next_event() == EndOfMessage() + + +def test_client_talking_to_http10_server() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "example.com")])) + c.send(EndOfMessage()) + assert c.our_state is DONE + # No content-length, so Http10 framing for body + assert receive_and_get(c, b"HTTP/1.0 200 OK\r\n\r\n") == [ + Response(status_code=200, headers=[], http_version="1.0", reason=b"OK") + ] + assert c.our_state is MUST_CLOSE + assert receive_and_get(c, b"12345") == [Data(data=b"12345")] + assert receive_and_get(c, b"67890") == [Data(data=b"67890")] + assert receive_and_get(c, b"") == [EndOfMessage(), ConnectionClosed()] + assert c.their_state is CLOSED + + +def test_server_talking_to_http10_client() -> None: + c = Connection(SERVER) + # No content-length, so no body + # NB: no host header + assert receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + assert c.their_state is MUST_CLOSE + + # We automatically Connection: close back at them + assert ( + c.send(Response(status_code=200, headers=[])) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + + assert c.send(Data(data=b"12345")) == b"12345" + assert c.send(EndOfMessage()) == b"" + assert c.our_state is MUST_CLOSE + + # Check that it works if they do send Content-Length + c = Connection(SERVER) + # NB: no host header + assert receive_and_get(c, b"POST / HTTP/1.0\r\nContent-Length: 10\r\n\r\n1") == [ + Request( + method="POST", + target="/", + headers=[("Content-Length", "10")], + http_version="1.0", + ), + Data(data=b"1"), + ] + assert receive_and_get(c, b"234567890") == [Data(data=b"234567890"), EndOfMessage()] + assert c.their_state is MUST_CLOSE + assert receive_and_get(c, b"") == [ConnectionClosed()] + + +def test_automatic_transfer_encoding_in_response() -> None: + # Check that in responses, the user can specify either Transfer-Encoding: + # chunked or no framing at all, and in both cases we automatically select + # the right option depending on whether the peer speaks HTTP/1.0 or + # HTTP/1.1 + for user_headers in [ + [("Transfer-Encoding", "chunked")], + [], + # In fact, this even works if Content-Length is set, + # because if both are set then Transfer-Encoding wins + [("Transfer-Encoding", "chunked"), ("Content-Length", "100")], + ]: + user_headers = cast(List[Tuple[str, str]], user_headers) + p = ConnectionPair() + p.send( + CLIENT, + [ + Request(method="GET", target="/", headers=[("Host", "example.com")]), + EndOfMessage(), + ], + ) + # When speaking to HTTP/1.1 client, all of the above cases get + # normalized to Transfer-Encoding: chunked + p.send( + SERVER, + Response(status_code=200, headers=user_headers), + expect=Response( + status_code=200, headers=[("Transfer-Encoding", "chunked")] + ), + ) + + # When speaking to HTTP/1.0 client, all of the above cases get + # normalized to no-framing-headers + c = Connection(SERVER) + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert ( + c.send(Response(status_code=200, headers=user_headers)) + == b"HTTP/1.1 200 \r\nConnection: close\r\n\r\n" + ) + assert c.send(Data(data=b"12345")) == b"12345" + + +def test_automagic_connection_close_handling() -> None: + p = ConnectionPair() + # If the user explicitly sets Connection: close, then we notice and + # respect it + p.send( + CLIENT, + [ + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Connection", "close")], + ), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states[CLIENT] is MUST_CLOSE + # And if the client sets it, the server automatically echoes it back + p.send( + SERVER, + # no header here... + [Response(status_code=204, headers=[]), EndOfMessage()], + # ...but oh look, it arrived anyway + expect=[ + Response(status_code=204, headers=[("connection", "close")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_100_continue() -> None: + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", + target="/", + headers=[ + ("Host", "example.com"), + ("Content-Length", "100"), + ("Expect", "100-continue"), + ], + ), + ) + for conn in p.conns: + assert conn.client_is_waiting_for_100_continue + assert not p.conn[CLIENT].they_are_waiting_for_100_continue + assert p.conn[SERVER].they_are_waiting_for_100_continue + return p + + # Disabled by 100 Continue + p = setup() + p.send(SERVER, InformationalResponse(status_code=100, headers=[])) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by a real response + p = setup() + p.send( + SERVER, Response(status_code=200, headers=[("Transfer-Encoding", "chunked")]) + ) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + # Disabled by the client going ahead and sending stuff anyway + p = setup() + p.send(CLIENT, Data(data=b"12345")) + for conn in p.conns: + assert not conn.client_is_waiting_for_100_continue + assert not conn.they_are_waiting_for_100_continue + + +def test_max_incomplete_event_size_countermeasure() -> None: + # Infinitely long headers are definitely not okay + c = Connection(SERVER) + c.receive_data(b"GET / HTTP/1.0\r\nEndless: ") + assert c.next_event() is NEED_DATA + with pytest.raises(RemoteProtocolError): + while True: + c.receive_data(b"a" * 1024) + c.next_event() + + # Checking that the same header is accepted / rejected depending on the + # max_incomplete_event_size setting: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + c.receive_data(b"\r\n\r\n") + assert get_all_events(c) == [ + Request( + method="GET", target="/", http_version="1.0", headers=[("big", "a" * 4000)] + ), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=4000) + c.receive_data(b"GET / HTTP/1.0\r\nBig: ") + c.receive_data(b"a" * 4000) + with pytest.raises(RemoteProtocolError): + c.next_event() + + # Temporarily exceeding the size limit is fine, as long as its done with + # complete events: + c = Connection(SERVER, max_incomplete_event_size=5000) + c.receive_data(b"GET / HTTP/1.0\r\nContent-Length: 10000") + c.receive_data(b"\r\n\r\n" + b"a" * 10000) + assert get_all_events(c) == [ + Request( + method="GET", + target="/", + http_version="1.0", + headers=[("Content-Length", "10000")], + ), + Data(data=b"a" * 10000), + EndOfMessage(), + ] + + c = Connection(SERVER, max_incomplete_event_size=100) + # Two pipelined requests to create a way-too-big receive buffer... but + # it's fine because we're not checking + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a\r\n\r\n" + b"GET /2 HTTP/1.1\r\nHost: b\r\n\r\n" + b"X" * 1000 + ) + assert get_all_events(c) == [ + Request(method="GET", target="/1", headers=[("host", "a")]), + EndOfMessage(), + ] + # Even more data comes in, still no problem + c.receive_data(b"X" * 1000) + # We can respond and reuse to get the second pipelined request + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + assert get_all_events(c) == [ + Request(method="GET", target="/2", headers=[("host", "b")]), + EndOfMessage(), + ] + # But once we unpause and try to read the next message, and find that it's + # incomplete and the buffer is *still* way too large, then *that's* a + # problem: + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_reuse_simple() -> None: + p = ConnectionPair() + p.send( + CLIENT, + [Request(method="GET", target="/", headers=[("Host", "a")]), EndOfMessage()], + ) + p.send( + SERVER, + [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: DONE} + conn.start_next_cycle() + + p.send( + CLIENT, + [ + Request(method="DELETE", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ], + ) + p.send( + SERVER, + [ + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ], + ) + + +def test_pipelining() -> None: + # Client doesn't support pipelining, so we have to do this by hand + c = Connection(SERVER) + assert c.next_event() is NEED_DATA + # 3 requests all bunched up + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + b"GET /3 HTTP/1.1\r\nHost: a.com\r\n\r\n" + ) + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.their_state is DONE + assert c.our_state is SEND_RESPONSE + + assert c.next_event() is PAUSED + + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.their_state is DONE + assert c.our_state is DONE + + c.start_next_cycle() + + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("Host", "a.com"), ("Content-Length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ] + assert c.next_event() is PAUSED + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + c.start_next_cycle() + + assert get_all_events(c) == [ + Request(method="GET", target="/3", headers=[("Host", "a.com")]), + EndOfMessage(), + ] + # Doesn't pause this time, no trailing data + assert c.next_event() is NEED_DATA + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + + # Arrival of more data triggers pause + assert c.next_event() is NEED_DATA + c.receive_data(b"SADF") + assert c.next_event() is PAUSED + assert c.trailing_data == (b"SADF", False) + # If EOF arrives while paused, we don't see that either: + c.receive_data(b"") + assert c.trailing_data == (b"SADF", True) + assert c.next_event() is PAUSED + c.receive_data(b"") + assert c.next_event() is PAUSED + # Can't call receive_data with non-empty buf after closing it + with pytest.raises(RuntimeError): + c.receive_data(b"FDSA") + + +def test_protocol_switch() -> None: + for req, deny, accept in [ + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + InformationalResponse(status_code=101, headers=[("Upgrade", "a")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept CONNECT, not upgrade + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + ), + ( + Request( + method="CONNECT", + target="example.com:443", + headers=[("Host", "foo"), ("Content-Length", "1"), ("Upgrade", "a, b")], + ), + Response(status_code=404, headers=[(b"transfer-encoding", b"chunked")]), + # Accept Upgrade, not CONNECT + InformationalResponse(status_code=101, headers=[("Upgrade", "b")]), + ), + ]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(CLIENT, req) + # No switch-related state change stuff yet; the client has to + # finish the request before that kicks in + for conn in p.conns: + assert conn.states[CLIENT] is SEND_BODY + p.send(CLIENT, [Data(data=b"1"), EndOfMessage()]) + for conn in p.conns: + assert conn.states[CLIENT] is MIGHT_SWITCH_PROTOCOL + assert p.conn[SERVER].next_event() is PAUSED + return p + + # Test deny case + p = setup() + p.send(SERVER, deny) + for conn in p.conns: + assert conn.states == {CLIENT: DONE, SERVER: SEND_BODY} + p.send(SERVER, EndOfMessage()) + # Check that re-use is still allowed after a denial + for conn in p.conns: + conn.start_next_cycle() + + # Test accept case + p = setup() + p.send(SERVER, accept) + for conn in p.conns: + assert conn.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + conn.receive_data(b"123") + assert conn.next_event() is PAUSED + conn.receive_data(b"456") + assert conn.next_event() is PAUSED + assert conn.trailing_data == (b"123456", False) + + # Pausing in might-switch, then recovery + # (weird artificial case where the trailing data actually is valid + # HTTP for some reason, because this makes it easier to test the state + # logic) + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"GET / HTTP/1.0\r\n\r\n") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"GET / HTTP/1.0\r\n\r\n", False) + sc.send(deny) + assert sc.next_event() is PAUSED + sc.send(EndOfMessage()) + sc.start_next_cycle() + assert get_all_events(sc) == [ + Request(method="GET", target="/", headers=[], http_version="1.0"), + EndOfMessage(), + ] + + # When we're DONE, have no trailing data, and the connection gets + # closed, we report ConnectionClosed(). When we're in might-switch or + # switched, we don't. + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + assert sc.trailing_data == (b"", True) + p.send(SERVER, accept) + assert sc.next_event() is PAUSED + + p = setup() + sc = p.conn[SERVER] + sc.receive_data(b"") + assert sc.next_event() is PAUSED + sc.send(deny) + assert sc.next_event() == ConnectionClosed() + + # You can't send after switching protocols, or while waiting for a + # protocol switch + p = setup() + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send( + Request(method="GET", target="/", headers=[("Host", "a")]) + ) + p = setup() + p.send(SERVER, accept) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(Data(data=b"123")) + + +def test_close_simple() -> None: + # Just immediately closing a new connection without anything having + # happened yet. + for who_shot_first, who_shot_second in [(CLIENT, SERVER), (SERVER, CLIENT)]: + + def setup() -> ConnectionPair: + p = ConnectionPair() + p.send(who_shot_first, ConnectionClosed()) + for conn in p.conns: + assert conn.states == { + who_shot_first: CLOSED, + who_shot_second: MUST_CLOSE, + } + return p + + # You can keep putting b"" into a closed connection, and you keep + # getting ConnectionClosed() out: + p = setup() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + p.conn[who_shot_second].receive_data(b"") + assert p.conn[who_shot_second].next_event() == ConnectionClosed() + # Second party can close... + p = setup() + p.send(who_shot_second, ConnectionClosed()) + for conn in p.conns: + assert conn.our_state is CLOSED + assert conn.their_state is CLOSED + # But trying to receive new data on a closed connection is a + # RuntimeError (not ProtocolError, because the problem here isn't + # violation of HTTP, it's violation of physics) + p = setup() + with pytest.raises(RuntimeError): + p.conn[who_shot_second].receive_data(b"123") + # And receiving new data on a MUST_CLOSE connection is a ProtocolError + p = setup() + p.conn[who_shot_first].receive_data(b"GET") + with pytest.raises(RemoteProtocolError): + p.conn[who_shot_first].next_event() + + +def test_close_different_states() -> None: + req = [ + Request(method="GET", target="/foo", headers=[("Host", "a")]), + EndOfMessage(), + ] + resp = [ + Response(status_code=200, headers=[(b"transfer-encoding", b"chunked")]), + EndOfMessage(), + ] + + # Client before request + p = ConnectionPair() + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + + # Client after request + p = ConnectionPair() + p.send(CLIENT, req) + p.send(CLIENT, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + + # Server after request -> not allowed + p = ConnectionPair() + p.send(CLIENT, req) + with pytest.raises(LocalProtocolError): + p.conn[SERVER].send(ConnectionClosed()) + p.conn[CLIENT].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[CLIENT].next_event() + + # Server after response + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(SERVER, ConnectionClosed()) + for conn in p.conns: + assert conn.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + # Both after closing (ConnectionClosed() is idempotent) + p = ConnectionPair() + p.send(CLIENT, req) + p.send(SERVER, resp) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + p.send(CLIENT, ConnectionClosed()) + p.send(SERVER, ConnectionClosed()) + + # In the middle of sending -> not allowed + p = ConnectionPair() + p.send( + CLIENT, + Request( + method="GET", target="/", headers=[("Host", "a"), ("Content-Length", "10")] + ), + ) + with pytest.raises(LocalProtocolError): + p.conn[CLIENT].send(ConnectionClosed()) + p.conn[SERVER].receive_data(b"") + with pytest.raises(RemoteProtocolError): + p.conn[SERVER].next_event() + + +# Receive several requests and then client shuts down their side of the +# connection; we can respond to each +def test_pipelined_close() -> None: + c = Connection(SERVER) + # 2 requests then a close + c.receive_data( + b"GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"12345" + b"GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n" + b"67890" + ) + c.receive_data(b"") + assert get_all_events(c) == [ + Request( + method="GET", + target="/1", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"12345"), + EndOfMessage(), + ] + assert c.states[CLIENT] is DONE + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states[SERVER] is DONE + c.start_next_cycle() + assert get_all_events(c) == [ + Request( + method="GET", + target="/2", + headers=[("host", "a.com"), ("content-length", "5")], + ), + Data(data=b"67890"), + EndOfMessage(), + ConnectionClosed(), + ] + assert c.states == {CLIENT: CLOSED, SERVER: SEND_RESPONSE} + c.send(Response(status_code=200, headers=[])) + c.send(EndOfMessage()) + assert c.states == {CLIENT: CLOSED, SERVER: MUST_CLOSE} + c.send(ConnectionClosed()) + assert c.states == {CLIENT: CLOSED, SERVER: CLOSED} + + +def test_sendfile() -> None: + class SendfilePlaceholder: + def __len__(self) -> int: + return 10 + + placeholder = SendfilePlaceholder() + + def setup( + header: Tuple[str, str], http_version: str + ) -> Tuple[Connection, Optional[List[bytes]]]: + c = Connection(SERVER) + receive_and_get( + c, f"GET / HTTP/{http_version}\r\nHost: a\r\n\r\n".encode("ascii") + ) + headers = [] + if header: + headers.append(header) + c.send(Response(status_code=200, headers=headers)) + return c, c.send_with_data_passthrough(Data(data=placeholder)) # type: ignore + + c, data = setup(("Content-Length", "10"), "1.1") + assert data == [placeholder] # type: ignore + # Raises an error if the connection object doesn't think we've sent + # exactly 10 bytes + c.send(EndOfMessage()) + + _, data = setup(("Transfer-Encoding", "chunked"), "1.1") + assert placeholder in data # type: ignore + data[data.index(placeholder)] = b"x" * 10 # type: ignore + assert b"".join(data) == b"a\r\nxxxxxxxxxx\r\n" # type: ignore + + c, data = setup(None, "1.0") # type: ignore + assert data == [placeholder] # type: ignore + assert c.our_state is SEND_BODY + + +def test_errors() -> None: + # After a receive error, you can't receive + for role in [CLIENT, SERVER]: + c = Connection(our_role=role) + c.receive_data(b"gibberish\r\n\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + # Now any attempt to receive continues to raise + assert c.their_state is ERROR + assert c.our_state is not ERROR + print(c._cstate.states) + with pytest.raises(RemoteProtocolError): + c.next_event() + # But we can still yell at the client for sending us gibberish + if role is SERVER: + assert ( + c.send(Response(status_code=400, headers=[])) + == b"HTTP/1.1 400 \r\nConnection: close\r\n\r\n" + ) + + # After an error sending, you can no longer send + # (This is especially important for things like content-length errors, + # where there's complex internal state being modified) + def conn(role: Type[Sentinel]) -> Connection: + c = Connection(our_role=role) + if role is SERVER: + # Put it into the state where it *could* send a response... + receive_and_get(c, b"GET / HTTP/1.0\r\n\r\n") + assert c.our_state is SEND_RESPONSE + return c + + for role in [CLIENT, SERVER]: + if role is CLIENT: + # This HTTP/1.0 request won't be detected as bad until after we go + # through the state machine and hit the writing code + good = Request(method="GET", target="/", headers=[("Host", "example.com")]) + bad = Request( + method="GET", + target="/", + headers=[("Host", "example.com")], + http_version="1.0", + ) + elif role is SERVER: + good = Response(status_code=200, headers=[]) # type: ignore[assignment] + bad = Response(status_code=200, headers=[], http_version="1.0") # type: ignore[assignment] + # Make sure 'good' actually is good + c = conn(role) + c.send(good) + assert c.our_state is not ERROR + # Do that again, but this time sending 'bad' first + c = conn(role) + with pytest.raises(LocalProtocolError): + c.send(bad) + assert c.our_state is ERROR + assert c.their_state is not ERROR + # Now 'good' is not so good + with pytest.raises(LocalProtocolError): + c.send(good) + + # And check send_failed() too + c = conn(role) + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + # This is idempotent + c.send_failed() + assert c.our_state is ERROR + assert c.their_state is not ERROR + + +def test_idle_receive_nothing() -> None: + # At one point this incorrectly raised an error + for role in [CLIENT, SERVER]: + c = Connection(role) + assert c.next_event() is NEED_DATA + + +def test_connection_drop() -> None: + c = Connection(SERVER) + c.receive_data(b"GET /") + assert c.next_event() is NEED_DATA + c.receive_data(b"") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +def test_408_request_timeout() -> None: + # Should be able to send this spontaneously as a server without seeing + # anything from client + p = ConnectionPair() + p.send(SERVER, Response(status_code=408, headers=[(b"connection", b"close")])) + + +# This used to raise IndexError +def test_empty_request() -> None: + c = Connection(SERVER) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to raise IndexError +def test_empty_response() -> None: + c = Connection(CLIENT) + c.send(Request(method="GET", target="/", headers=[("Host", "a")])) + c.receive_data(b"\r\n") + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x01\x00\xa5", # Typical start of a TLS Client Hello + ], +) +def test_early_detection_of_invalid_request(data: bytes) -> None: + c = Connection(SERVER) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +@pytest.mark.parametrize( + "data", + [ + b"\x00", + b"\x20", + b"\x16\x03\x03\x00\x31", # Typical start of a TLS Server Hello + ], +) +def test_early_detection_of_invalid_response(data: bytes) -> None: + c = Connection(CLIENT) + # Early detection should occur before even receiving a `\r\n` + c.receive_data(data) + with pytest.raises(RemoteProtocolError): + c.next_event() + + +# This used to give different headers for HEAD and GET. +# The correct way to handle HEAD is to put whatever headers we *would* have +# put if it were a GET -- even though we know that for HEAD, those headers +# will be ignored. +def test_HEAD_framing_headers() -> None: + def setup(method: bytes, http_version: bytes) -> Connection: + c = Connection(SERVER) + c.receive_data( + method + b" / HTTP/" + http_version + b"\r\n" + b"Host: example.com\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert type(c.next_event()) is EndOfMessage + return c + + for method in [b"GET", b"HEAD"]: + # No Content-Length, HTTP/1.1 peer, should use chunked + c = setup(method, b"1.1") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + # No Content-Length, HTTP/1.0 peer, frame with connection: close + c = setup(method, b"1.0") + assert ( + c.send(Response(status_code=200, headers=[])) == b"HTTP/1.1 200 \r\n" + b"Connection: close\r\n\r\n" + ) + + # Content-Length + Transfer-Encoding, TE wins + c = setup(method, b"1.1") + assert ( + c.send( + Response( + status_code=200, + headers=[ + ("Content-Length", "100"), + ("Transfer-Encoding", "chunked"), + ], + ) + ) + == b"HTTP/1.1 200 \r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + + +def test_special_exceptions_for_lost_connection_in_message_body() -> None: + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" b"Host: example.com\r\n" b"Content-Length: 100\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"12345") + assert c.next_event() == Data(data=b"12345") + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "received 5 bytes" in str(excinfo.value) + assert "expected 100" in str(excinfo.value) + + c = Connection(SERVER) + c.receive_data( + b"POST / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Transfer-Encoding: chunked\r\n\r\n" + ) + assert type(c.next_event()) is Request + assert c.next_event() is NEED_DATA + c.receive_data(b"8\r\n012345") + assert c.next_event().data == b"012345" # type: ignore + c.receive_data(b"") + with pytest.raises(RemoteProtocolError) as excinfo: + c.next_event() + assert "incomplete chunked read" in str(excinfo.value) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_events.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..d6915457047b7d5fdffb419ef7ccde9dfaa72e05 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_events.py @@ -0,0 +1,148 @@ +from http import HTTPStatus + +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + InformationalResponse, + Request, + Response, +) +from .._util import LocalProtocolError + + +def test_events() -> None: + with pytest.raises(LocalProtocolError): + # Missing Host: + req = Request( + method="GET", target="/", headers=[("a", "b")], http_version="1.1" + ) + # But this is okay (HTTP/1.0) + req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") + # fields are normalized + assert req.method == b"GET" + assert req.target == b"/" + assert req.headers == [(b"a", b"b")] + assert req.http_version == b"1.0" + + # This is also okay -- has a Host (with weird capitalization, which is ok) + req = Request( + method="GET", + target="/", + headers=[("a", "b"), ("hOSt", "example.com")], + http_version="1.1", + ) + # we normalize header capitalization + assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] + + # Multiple host is bad too + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.1", + ) + # Even for HTTP/1.0 + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Host", "a")], + http_version="1.0", + ) + + # Header values are validated + for bad_char in "\x00\r\n\f\v": + with pytest.raises(LocalProtocolError): + req = Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd" + bad_char)], + http_version="1.0", + ) + + # But for compatibility we allow non-whitespace control characters, even + # though they're forbidden by the spec. + Request( + method="GET", + target="/", + headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], + http_version="1.0", + ) + + # Request target is validated + for bad_byte in b"\x00\x20\x7f\xee": + target = bytearray(b"/") + target.append(bad_byte) + with pytest.raises(LocalProtocolError): + Request( + method="GET", target=target, headers=[("Host", "a")], http_version="1.1" + ) + + # Request method is validated + with pytest.raises(LocalProtocolError): + Request( + method="GET / HTTP/1.1", + target=target, + headers=[("Host", "a")], + http_version="1.1", + ) + + ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) + assert ir.status_code == 100 + assert ir.headers == [(b"host", b"a")] + assert ir.http_version == b"1.1" + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=200, headers=[("Host", "a")]) + + resp = Response(status_code=204, headers=[], http_version="1.0") + assert resp.status_code == 204 + assert resp.headers == [] + assert resp.http_version == b"1.0" + + with pytest.raises(LocalProtocolError): + resp = Response(status_code=100, headers=[], http_version="1.0") + + with pytest.raises(LocalProtocolError): + Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] + + with pytest.raises(LocalProtocolError): + InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] + + d = Data(data=b"asdf") + assert d.data == b"asdf" + + eom = EndOfMessage() + assert eom.headers == [] + + cc = ConnectionClosed() + assert repr(cc) == "ConnectionClosed()" + + +def test_intenum_status_code() -> None: + # https://github.com/python-hyper/h11/issues/72 + + r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") + assert r.status_code == HTTPStatus.OK + assert type(r.status_code) is not type(HTTPStatus.OK) + assert type(r.status_code) is int + + +def test_header_casing() -> None: + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert len(r.headers) == 2 + assert r.headers[0] == (b"host", b"example.org") + assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_headers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53d088f6f8d22dede47873a03b70a7103da7ea --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_headers.py @@ -0,0 +1,157 @@ +import pytest + +from .._events import Request +from .._headers import ( + get_comma_header, + has_expect_100_continue, + Headers, + normalize_and_validate, + set_comma_header, +) +from .._util import LocalProtocolError + + +def test_normalize_and_validate() -> None: + assert normalize_and_validate([("foo", "bar")]) == [(b"foo", b"bar")] + assert normalize_and_validate([(b"foo", b"bar")]) == [(b"foo", b"bar")] + + # no leading/trailing whitespace in names + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo ", "bar")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b" foo", "bar")]) + + # no weird characters in names + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([(b"foo bar", b"baz")]) + assert "foo bar" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x00bar", b"baz")]) + # Not even 8-bit characters: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\xffbar", b"baz")]) + # And not even the control characters we allow in values: + with pytest.raises(LocalProtocolError): + normalize_and_validate([(b"foo\x01bar", b"baz")]) + + # no return or NUL characters in values + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("foo", "bar\rbaz")]) + assert "bar\\rbaz" in str(excinfo.value) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\nbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "bar\x00baz")]) + # no leading/trailing whitespace + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz ")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", " barbaz")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "barbaz\t")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("foo", "\tbarbaz")]) + + # content-length + assert normalize_and_validate([("Content-Length", "1")]) == [ + (b"content-length", b"1") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "asdf")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1x")]) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1"), ("Content-Length", "2")]) + assert normalize_and_validate( + [("Content-Length", "0"), ("Content-Length", "0")] + ) == [(b"content-length", b"0")] + assert normalize_and_validate([("Content-Length", "0 , 0")]) == [ + (b"content-length", b"0") + ] + with pytest.raises(LocalProtocolError): + normalize_and_validate( + [("Content-Length", "1"), ("Content-Length", "1"), ("Content-Length", "2")] + ) + with pytest.raises(LocalProtocolError): + normalize_and_validate([("Content-Length", "1 , 1,2")]) + + # transfer-encoding + assert normalize_and_validate([("Transfer-Encoding", "chunked")]) == [ + (b"transfer-encoding", b"chunked") + ] + assert normalize_and_validate([("Transfer-Encoding", "cHuNkEd")]) == [ + (b"transfer-encoding", b"chunked") + ] + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate([("Transfer-Encoding", "gzip")]) + assert excinfo.value.error_status_hint == 501 # Not Implemented + with pytest.raises(LocalProtocolError) as excinfo: + normalize_and_validate( + [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "gzip")] + ) + assert excinfo.value.error_status_hint == 501 # Not Implemented + + +def test_get_set_comma_header() -> None: + headers = normalize_and_validate( + [ + ("Connection", "close"), + ("whatever", "something"), + ("connectiON", "fOo,, , BAR"), + ] + ) + + assert get_comma_header(headers, b"connection") == [b"close", b"foo", b"bar"] + + headers = set_comma_header(headers, b"newthing", ["a", "b"]) # type: ignore + + with pytest.raises(LocalProtocolError): + set_comma_header(headers, b"newthing", [" a", "b"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"whatever", b"something"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + ] + + headers = set_comma_header(headers, b"whatever", ["different thing"]) # type: ignore + + assert headers == [ + (b"connection", b"close"), + (b"connection", b"fOo,, , BAR"), + (b"newthing", b"a"), + (b"newthing", b"b"), + (b"whatever", b"different thing"), + ] + + +def test_has_100_continue() -> None: + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + ) + ) + assert not has_expect_100_continue( + Request(method="GET", target="/", headers=[("Host", "example.com")]) + ) + # Case insensitive + assert has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-Continue")], + ) + ) + # Doesn't work in HTTP/1.0 + assert not has_expect_100_continue( + Request( + method="GET", + target="/", + headers=[("Host", "example.com"), ("Expect", "100-continue")], + http_version="1.0", + ) + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_helpers.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9a30dc655445c48d08ad36c6948ddf27a15178fe --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_helpers.py @@ -0,0 +1,24 @@ +from .._events import Data, EndOfMessage, Response +from .helpers import normalize_data_events + + +def test_normalize_data_events() -> None: + assert normalize_data_events( + [ + Data(data=bytearray(b"1")), + Data(data=b"2"), + Response(status_code=200, headers=[]), + Data(data=b"3"), + Data(data=b"4"), + EndOfMessage(), + Data(data=b"5"), + Data(data=b"6"), + Data(data=b"7"), + ] + ) == [ + Data(data=b"12"), + Response(status_code=200, headers=[]), + Data(data=b"34"), + EndOfMessage(), + Data(data=b"567"), + ] diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_io.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..42137b09ff3c7d10728d9978dc5e054f1578cf00 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_io.py @@ -0,0 +1,560 @@ +from typing import Any, Callable, Generator, List + +import pytest + +from .._events import ( + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._headers import Headers, normalize_and_validate +from .._readers import ( + _obsolete_line_fold, + ChunkedReader, + ContentLengthReader, + Http10Reader, + READERS, +) +from .._receivebuffer import ReceiveBuffer +from .._state import CLIENT, IDLE, SEND_RESPONSE, SERVER +from .._util import LocalProtocolError +from .._writers import ( + ChunkedWriter, + ContentLengthWriter, + Http10Writer, + write_any_response, + write_headers, + write_request, + WRITERS, +) +from .helpers import normalize_data_events + +SIMPLE_CASES = [ + ( + (CLIENT, IDLE), + Request( + method="GET", + target="/a", + headers=[("Host", "foo"), ("Connection", "close")], + ), + b"GET /a HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[("Connection", "close")], reason=b"OK"), + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + Response(status_code=200, headers=[], reason=b"OK"), + b"HTTP/1.1 200 OK\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse( + status_code=101, headers=[("Upgrade", "websocket")], reason=b"Upgrade" + ), + b"HTTP/1.1 101 Upgrade\r\nUpgrade: websocket\r\n\r\n", + ), + ( + (SERVER, SEND_RESPONSE), + InformationalResponse(status_code=101, headers=[], reason=b"Upgrade"), + b"HTTP/1.1 101 Upgrade\r\n\r\n", + ), +] + + +def dowrite(writer: Callable[..., None], obj: Any) -> bytes: + got_list: List[bytes] = [] + writer(obj, got_list.append) + return b"".join(got_list) + + +def tw(writer: Any, obj: Any, expected: Any) -> None: + got = dowrite(writer, obj) + assert got == expected + + +def makebuf(data: bytes) -> ReceiveBuffer: + buf = ReceiveBuffer() + buf += data + return buf + + +def tr(reader: Any, data: bytes, expected: Any) -> None: + def check(got: Any) -> None: + assert got == expected + # Headers should always be returned as bytes, not e.g. bytearray + # https://github.com/python-hyper/wsproto/pull/54#issuecomment-377709478 + for name, value in getattr(got, "headers", []): + assert type(name) is bytes + assert type(value) is bytes + + # Simple: consume whole thing + buf = makebuf(data) + check(reader(buf)) + assert not buf + + # Incrementally growing buffer + buf = ReceiveBuffer() + for i in range(len(data)): + assert reader(buf) is None + buf += data[i : i + 1] + check(reader(buf)) + + # Trailing data + buf = makebuf(data) + buf += b"trailing" + check(reader(buf)) + assert bytes(buf) == b"trailing" + + +def test_writers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tw(WRITERS[role, state], event, binary) + + +def test_readers_simple() -> None: + for (role, state), event, binary in SIMPLE_CASES: + tr(READERS[role, state], binary, event) + + +def test_writers_unusual() -> None: + # Simple test of the write_headers utility routine + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("baz", "quux")]), + b"foo: bar\r\nbaz: quux\r\n\r\n", + ) + tw(write_headers, Headers([]), b"\r\n") + + # We understand HTTP/1.0, but we don't speak it + with pytest.raises(LocalProtocolError): + tw( + write_request, + Request( + method="GET", + target="/", + headers=[("Host", "foo"), ("Connection", "close")], + http_version="1.0", + ), + None, + ) + with pytest.raises(LocalProtocolError): + tw( + write_any_response, + Response( + status_code=200, headers=[("Connection", "close")], http_version="1.0" + ), + None, + ) + + +def test_readers_unusual() -> None: + # Reading HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\nSome: header\r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[("Some", "header")], + http_version="1.0", + ), + ) + + # check no-headers, since it's only legal with HTTP/1.0 + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.0\r\n\r\n", + Request(method="HEAD", target="/foo", headers=[], http_version="1.0"), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\nSome: header\r\n\r\n", + Response( + status_code=200, + headers=[("Some", "header")], + http_version="1.0", + reason=b"OK", + ), + ) + + # single-character header values (actually disallowed by the ABNF in RFC + # 7230 -- this is a bug in the standard that we originally copied...) + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: a a a a a \r\n\r\n", + Response( + status_code=200, + headers=[("Foo", "a a a a a")], + http_version="1.0", + reason=b"OK", + ), + ) + + # Empty headers -- also legal + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo:\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200 OK\r\n" b"Foo: \t \t \r\n\r\n", + Response( + status_code=200, headers=[("Foo", "")], http_version="1.0", reason=b"OK" + ), + ) + + # Tolerate broken servers that leave off the response code + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.0 200\r\n" b"Foo: bar\r\n\r\n", + Response( + status_code=200, headers=[("Foo", "bar")], http_version="1.0", reason=b"" + ), + ) + + # Tolerate headers line endings (\r\n and \n) + # \n\r\b between headers and body + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader: val\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader", "val")], + http_version="1.1", + reason="OK", + ), + ) + + # delimited only with \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\nSomeHeader1: val1\nSomeHeader2: val2\n\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # mixed \r\n and \n + tr( + READERS[SERVER, SEND_RESPONSE], + b"HTTP/1.1 200 OK\r\nSomeHeader1: val1\nSomeHeader2: val2\n\r\n", + Response( + status_code=200, + headers=[("SomeHeader1", "val1"), ("SomeHeader2", "val2")], + http_version="1.1", + reason="OK", + ), + ) + + # obsolete line folding + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Some: multi-line\r\n" + b" header\r\n" + b"\tnonsense\r\n" + b" \t \t\tI guess\r\n" + b"Connection: close\r\n" + b"More-nonsense: in the\r\n" + b" last header \r\n\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "example.com"), + ("Some", "multi-line header nonsense I guess"), + ("Connection", "close"), + ("More-nonsense", "in the last header"), + ], + ), + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b" folded: line\r\n\r\n", + None, + ) + + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo : line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"foo\t: line\r\n\r\n", + None, + ) + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], b"HEAD /foo HTTP/1.1\r\n" b": line\r\n\r\n", None) + + +def test__obsolete_line_fold_bytes() -> None: + # _obsolete_line_fold has a defensive cast to bytearray, which is + # necessary to protect against O(n^2) behavior in case anyone ever passes + # in regular bytestrings... but right now we never pass in regular + # bytestrings. so this test just exists to get some coverage on that + # defensive cast. + assert list(_obsolete_line_fold([b"aaa", b"bbb", b" ccc", b"ddd"])) == [ + b"aaa", + bytearray(b"bbb ccc"), + b"ddd", + ] + + +def _run_reader_iter( + reader: Any, buf: bytes, do_eof: bool +) -> Generator[Any, None, None]: + while True: + event = reader(buf) + if event is None: + break + yield event + # body readers have undefined behavior after returning EndOfMessage, + # because this changes the state so they don't get called again + if type(event) is EndOfMessage: + break + if do_eof: + assert not buf + yield reader.read_eof() + + +def _run_reader(*args: Any) -> List[Event]: + events = list(_run_reader_iter(*args)) + return normalize_data_events(events) + + +def t_body_reader(thunk: Any, data: bytes, expected: Any, do_eof: bool = False) -> None: + # Simple: consume whole thing + print("Test 1") + buf = makebuf(data) + assert _run_reader(thunk(), buf, do_eof) == expected + + # Incrementally growing buffer + print("Test 2") + reader = thunk() + buf = ReceiveBuffer() + events = [] + for i in range(len(data)): + events += _run_reader(reader, buf, False) + buf += data[i : i + 1] + events += _run_reader(reader, buf, do_eof) + assert normalize_data_events(events) == expected + + is_complete = any(type(event) is EndOfMessage for event in expected) + if is_complete and not do_eof: + buf = makebuf(data + b"trailing") + assert _run_reader(thunk(), buf, False) == expected + + +def test_ContentLengthReader() -> None: + t_body_reader(lambda: ContentLengthReader(0), b"", [EndOfMessage()]) + + t_body_reader( + lambda: ContentLengthReader(10), + b"0123456789", + [Data(data=b"0123456789"), EndOfMessage()], + ) + + +def test_Http10Reader() -> None: + t_body_reader(Http10Reader, b"", [EndOfMessage()], do_eof=True) + t_body_reader(Http10Reader, b"asdf", [Data(data=b"asdf")], do_eof=False) + t_body_reader( + Http10Reader, b"asdf", [Data(data=b"asdf"), EndOfMessage()], do_eof=True + ) + + +def test_ChunkedReader() -> None: + t_body_reader(ChunkedReader, b"0\r\n\r\n", [EndOfMessage()]) + + t_body_reader( + ChunkedReader, + b"0\r\nSome: header\r\n\r\n", + [EndOfMessage(headers=[("Some", "header")])], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + + b"10\r\n0123456789abcdef\r\n" + + b"0\r\n" + + b"Some: header\r\n\r\n", + [ + Data(data=b"012340123456789abcdef"), + EndOfMessage(headers=[("Some", "header")]), + ], + ) + + t_body_reader( + ChunkedReader, + b"5\r\n01234\r\n" + b"10\r\n0123456789abcdef\r\n" + b"0\r\n\r\n", + [Data(data=b"012340123456789abcdef"), EndOfMessage()], + ) + + # handles upper and lowercase hex + t_body_reader( + ChunkedReader, + b"aA\r\n" + b"x" * 0xAA + b"\r\n" + b"0\r\n\r\n", + [Data(data=b"x" * 0xAA), EndOfMessage()], + ) + + # refuses arbitrarily long chunk integers + with pytest.raises(LocalProtocolError): + # Technically this is legal HTTP/1.1, but we refuse to process chunk + # sizes that don't fit into 20 characters of hex + t_body_reader(ChunkedReader, b"9" * 100 + b"\r\nxxx", [Data(data=b"xxx")]) + + # refuses garbage in the chunk count + with pytest.raises(LocalProtocolError): + t_body_reader(ChunkedReader, b"10\x00\r\nxxx", None) + + # handles (and discards) "chunk extensions" omg wtf + t_body_reader( + ChunkedReader, + b"5; hello=there\r\n" + + b"xxxxx" + + b"\r\n" + + b'0; random="junk"; some=more; canbe=lonnnnngg\r\n\r\n', + [Data(data=b"xxxxx"), EndOfMessage()], + ) + + t_body_reader( + ChunkedReader, + b"5 \r\n01234\r\n" + b"0\r\n\r\n", + [Data(data=b"01234"), EndOfMessage()], + ) + + +def test_ContentLengthWriter() -> None: + w = ContentLengthWriter(5) + assert dowrite(w, Data(data=b"123")) == b"123" + assert dowrite(w, Data(data=b"45")) == b"45" + assert dowrite(w, EndOfMessage()) == b"" + + w = ContentLengthWriter(5) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"123456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, Data(data=b"456")) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage()) + + w = ContentLengthWriter(5) + dowrite(w, Data(data=b"123")) == b"123" + dowrite(w, Data(data=b"45")) == b"45" + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_ChunkedWriter() -> None: + w = ChunkedWriter() + assert dowrite(w, Data(data=b"aaa")) == b"3\r\naaa\r\n" + assert dowrite(w, Data(data=b"a" * 20)) == b"14\r\n" + b"a" * 20 + b"\r\n" + + assert dowrite(w, Data(data=b"")) == b"" + + assert dowrite(w, EndOfMessage()) == b"0\r\n\r\n" + + assert ( + dowrite(w, EndOfMessage(headers=[("Etag", "asdf"), ("a", "b")])) + == b"0\r\nEtag: asdf\r\na: b\r\n\r\n" + ) + + +def test_Http10Writer() -> None: + w = Http10Writer() + assert dowrite(w, Data(data=b"1234")) == b"1234" + assert dowrite(w, EndOfMessage()) == b"" + + with pytest.raises(LocalProtocolError): + dowrite(w, EndOfMessage(headers=[("Etag", "asdf")])) + + +def test_reject_garbage_after_request_line() -> None: + with pytest.raises(LocalProtocolError): + tr(READERS[SERVER, SEND_RESPONSE], b"HTTP/1.0 200 OK\x00xxxx\r\n\r\n", None) + + +def test_reject_garbage_after_response_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1 xxxxxx\r\n" b"Host: a\r\n\r\n", + None, + ) + + +def test_reject_garbage_in_header_line() -> None: + with pytest.raises(LocalProtocolError): + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" b"Host: foo\x00bar\r\n\r\n", + None, + ) + + +def test_reject_non_vchar_in_path() -> None: + for bad_char in b"\x00\x20\x7f\xee": + message = bytearray(b"HEAD /") + message.append(bad_char) + message.extend(b" HTTP/1.1\r\nHost: foobar\r\n\r\n") + with pytest.raises(LocalProtocolError): + tr(READERS[CLIENT, IDLE], message, None) + + +# https://github.com/python-hyper/h11/issues/57 +def test_allow_some_garbage_in_cookies() -> None: + tr( + READERS[CLIENT, IDLE], + b"HEAD /foo HTTP/1.1\r\n" + b"Host: foo\r\n" + b"Set-Cookie: ___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900\r\n" + b"\r\n", + Request( + method="HEAD", + target="/foo", + headers=[ + ("Host", "foo"), + ("Set-Cookie", "___utmvafIumyLc=kUd\x01UpAt; path=/; Max-Age=900"), + ], + ), + ) + + +def test_host_comes_first() -> None: + tw( + write_headers, + normalize_and_validate([("foo", "bar"), ("Host", "example.com")]), + b"Host: example.com\r\nfoo: bar\r\n\r\n", + ) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_receivebuffer.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..21a3870b6be9a6a365037326c2085ff2715022cc --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_receivebuffer.py @@ -0,0 +1,135 @@ +import re +from typing import Tuple + +import pytest + +from .._receivebuffer import ReceiveBuffer + + +def test_receivebuffer() -> None: + b = ReceiveBuffer() + assert not b + assert len(b) == 0 + assert bytes(b) == b"" + + b += b"123" + assert b + assert len(b) == 3 + assert bytes(b) == b"123" + + assert bytes(b) == b"123" + + assert b.maybe_extract_at_most(2) == b"12" + assert b + assert len(b) == 1 + assert bytes(b) == b"3" + + assert bytes(b) == b"3" + + assert b.maybe_extract_at_most(10) == b"3" + assert bytes(b) == b"" + + assert b.maybe_extract_at_most(10) is None + assert not b + + ################################################################ + # maybe_extract_until_next + ################################################################ + + b += b"123\n456\r\n789\r\n" + + assert b.maybe_extract_next_line() == b"123\n456\r\n" + assert bytes(b) == b"789\r\n" + + assert b.maybe_extract_next_line() == b"789\r\n" + assert bytes(b) == b"" + + b += b"12\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r" + + b += b"345\n\r" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"12\r345\n\r" + + # here we stopped at the middle of b"\r\n" delimiter + + b += b"\n6789aaa123\r\n" + assert b.maybe_extract_next_line() == b"12\r345\n\r\n" + assert b.maybe_extract_next_line() == b"6789aaa123\r\n" + assert b.maybe_extract_next_line() is None + assert bytes(b) == b"" + + ################################################################ + # maybe_extract_lines + ################################################################ + + b += b"123\r\na: b\r\nfoo:bar\r\n\r\ntrailing" + lines = b.maybe_extract_lines() + assert lines == [b"123", b"a: b", b"foo:bar"] + assert bytes(b) == b"trailing" + + assert b.maybe_extract_lines() is None + + b += b"\r\n\r" + assert b.maybe_extract_lines() is None + + assert b.maybe_extract_at_most(100) == b"trailing\r\n\r" + assert not b + + # Empty body case (as happens at the end of chunked encoding if there are + # no trailing headers, e.g.) + b += b"\r\ntrailing" + assert b.maybe_extract_lines() == [] + assert bytes(b) == b"trailing" + + +@pytest.mark.parametrize( + "data", + [ + pytest.param( + ( + b"HTTP/1.1 200 OK\r\n", + b"Content-type: text/plain\r\n", + b"Connection: close\r\n", + b"\r\n", + b"Some body", + ), + id="with_crlf_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_lf_only_delimiter", + ), + pytest.param( + ( + b"HTTP/1.1 200 OK\n", + b"Content-type: text/plain\r\n", + b"Connection: close\n", + b"\n", + b"Some body", + ), + id="with_mixed_crlf_and_lf", + ), + ], +) +def test_receivebuffer_for_invalid_delimiter(data: Tuple[bytes]) -> None: + b = ReceiveBuffer() + + for line in data: + b += line + + lines = b.maybe_extract_lines() + + assert lines == [ + b"HTTP/1.1 200 OK", + b"Content-type: text/plain", + b"Connection: close", + ] + assert bytes(b) == b"Some body" diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_state.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bc974e636e9f3e9b66022d2095cd670a9acbdcd9 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_state.py @@ -0,0 +1,271 @@ +import pytest + +from .._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from .._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + CLOSED, + ConnectionState, + DONE, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from .._util import LocalProtocolError + + +def test_ConnectionState() -> None: + cs = ConnectionState() + + # Basic event-triggered transitions + + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + cs.process_event(CLIENT, Request) + # The SERVER-Request special case: + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # Illegal transitions raise an error and nothing happens + with pytest.raises(LocalProtocolError): + cs.process_event(CLIENT, Request) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_BODY} + + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: DONE, SERVER: DONE} + + # State-triggered transition + + cs.process_event(SERVER, ConnectionClosed) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: CLOSED} + + +def test_ConnectionState_keep_alive() -> None: + # keep_alive = False + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} + + +def test_ConnectionState_keep_alive_in_DONE() -> None: + # Check that if keep_alive is disabled when the CLIENT is already in DONE, + # then this is sufficient to immediately trigger the DONE -> MUST_CLOSE + # transition + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states[CLIENT] is DONE + cs.process_keep_alive_disabled() + assert cs.states[CLIENT] is MUST_CLOSE + + +def test_ConnectionState_switch_denied() -> None: + for switch_type in (_SWITCH_CONNECT, _SWITCH_UPGRADE): + for deny_early in (True, False): + cs = ConnectionState() + cs.process_client_switch_proposal(switch_type) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + assert switch_type in cs.pending_switch_proposals + + if deny_early: + # before client reaches DONE + cs.process_event(SERVER, Response) + assert not cs.pending_switch_proposals + + cs.process_event(CLIENT, EndOfMessage) + + if deny_early: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == { + CLIENT: MIGHT_SWITCH_PROTOCOL, + SERVER: SEND_RESPONSE, + } + + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + assert not cs.pending_switch_proposals + + +_response_type_for_switch = { + _SWITCH_UPGRADE: InformationalResponse, + _SWITCH_CONNECT: Response, + None: Response, +} + + +def test_ConnectionState_protocol_switch_accepted() -> None: + for switch_event in [_SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(switch_event) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, InformationalResponse) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + cs.process_event(SERVER, _response_type_for_switch[switch_event], switch_event) + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_double_protocol_switch() -> None: + # CONNECT + Upgrade is legal! Very silly, but legal. So we support + # it. Because sometimes doing the silly thing is easier than not. + for server_switch in [None, _SWITCH_UPGRADE, _SWITCH_CONNECT]: + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_client_switch_proposal(_SWITCH_CONNECT) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + cs.process_event( + SERVER, _response_type_for_switch[server_switch], server_switch + ) + if server_switch is None: + assert cs.states == {CLIENT: DONE, SERVER: SEND_BODY} + else: + assert cs.states == {CLIENT: SWITCHED_PROTOCOL, SERVER: SWITCHED_PROTOCOL} + + +def test_ConnectionState_inconsistent_protocol_switch() -> None: + for client_switches, server_switch in [ + ([], _SWITCH_CONNECT), + ([], _SWITCH_UPGRADE), + ([_SWITCH_UPGRADE], _SWITCH_CONNECT), + ([_SWITCH_CONNECT], _SWITCH_UPGRADE), + ]: + cs = ConnectionState() + for client_switch in client_switches: # type: ignore[attr-defined] + cs.process_client_switch_proposal(client_switch) + cs.process_event(CLIENT, Request) + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Response, server_switch) + + +def test_ConnectionState_keepalive_protocol_switch_interaction() -> None: + # keep_alive=False + pending_switch_proposals + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, Data) + assert cs.states == {CLIENT: SEND_BODY, SERVER: SEND_RESPONSE} + + # the protocol switch "wins" + cs.process_event(CLIENT, EndOfMessage) + assert cs.states == {CLIENT: MIGHT_SWITCH_PROTOCOL, SERVER: SEND_RESPONSE} + + # but when the server denies the request, keep_alive comes back into play + cs.process_event(SERVER, Response) + assert cs.states == {CLIENT: MUST_CLOSE, SERVER: SEND_BODY} + + +def test_ConnectionState_reuse() -> None: + cs = ConnectionState() + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + # No keepalive + + cs.process_event(CLIENT, Request) + cs.process_keep_alive_disabled() + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # One side closed + + cs = ConnectionState() + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(CLIENT, ConnectionClosed) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Succesful protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, InformationalResponse, _SWITCH_UPGRADE) + + with pytest.raises(LocalProtocolError): + cs.start_next_cycle() + + # Failed protocol switch + + cs = ConnectionState() + cs.process_client_switch_proposal(_SWITCH_UPGRADE) + cs.process_event(CLIENT, Request) + cs.process_event(CLIENT, EndOfMessage) + cs.process_event(SERVER, Response) + cs.process_event(SERVER, EndOfMessage) + + cs.start_next_cycle() + assert cs.states == {CLIENT: IDLE, SERVER: IDLE} + + +def test_server_request_is_illegal() -> None: + # There used to be a bug in how we handled the Request special case that + # made this allowed... + cs = ConnectionState() + with pytest.raises(LocalProtocolError): + cs.process_event(SERVER, Request) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_util.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc095185c79313b238fb034ef746c7f67b9d93 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/h11/tests/test_util.py @@ -0,0 +1,112 @@ +import re +import sys +import traceback +from typing import NoReturn + +import pytest + +from .._util import ( + bytesify, + LocalProtocolError, + ProtocolError, + RemoteProtocolError, + Sentinel, + validate, +) + + +def test_ProtocolError() -> None: + with pytest.raises(TypeError): + ProtocolError("abstract base class") + + +def test_LocalProtocolError() -> None: + try: + raise LocalProtocolError("foo") + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 400 + + try: + raise LocalProtocolError("foo", error_status_hint=418) + except LocalProtocolError as e: + assert str(e) == "foo" + assert e.error_status_hint == 418 + + def thunk() -> NoReturn: + raise LocalProtocolError("a", error_status_hint=420) + + try: + try: + thunk() + except LocalProtocolError as exc1: + orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + exc1._reraise_as_remote_protocol_error() + except RemoteProtocolError as exc2: + assert type(exc2) is RemoteProtocolError + assert exc2.args == ("a",) + assert exc2.error_status_hint == 420 + new_traceback = "".join(traceback.format_tb(sys.exc_info()[2])) + assert new_traceback.endswith(orig_traceback) + + +def test_validate() -> None: + my_re = re.compile(rb"(?P[0-9]+)\.(?P[0-9]+)") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.") + + groups = validate(my_re, b"0.1") + assert groups == {"group1": b"0", "group2": b"1"} + + # successful partial matches are an error - must match whole string + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1xx") + with pytest.raises(LocalProtocolError): + validate(my_re, b"0.1\n") + + +def test_validate_formatting() -> None: + my_re = re.compile(rb"foo") + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops") + assert "oops" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {}") + assert "oops {}" in str(excinfo.value) + + with pytest.raises(LocalProtocolError) as excinfo: + validate(my_re, b"", "oops {} xx", 10) + assert "oops 10 xx" in str(excinfo.value) + + +def test_make_sentinel() -> None: + class S(Sentinel, metaclass=Sentinel): + pass + + assert repr(S) == "S" + assert S == S + assert type(S).__name__ == "S" + assert S in {S} + assert type(S) is S + + class S2(Sentinel, metaclass=Sentinel): + pass + + assert repr(S2) == "S2" + assert S != S2 + assert S not in {S2} + assert type(S) is not type(S2) + + +def test_bytesify() -> None: + assert bytesify(b"123") == b"123" + assert bytesify(bytearray(b"123")) == b"123" + assert bytesify("123") == b"123" + + with pytest.raises(UnicodeEncodeError): + bytesify("\u1234") + + with pytest.raises(TypeError): + bytesify(10) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/pyproject.toml b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..64a6883338e47ed44bae176c52e575c4071a9a6b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/pyproject.toml @@ -0,0 +1,46 @@ +[tool.towncrier] +# Usage: +# - PRs should drop a file like "issuenumber.feature" in newsfragments +# (or "bugfix", "doc", "removal", "misc"; misc gets no text, we can +# customize this) +# - At release time after bumping version number, run: towncrier +# (or towncrier --draft) +package = "h11" +filename = "docs/source/changes.rst" +directory = "newsfragments" +underlines = ["-", "~", "^"] +issue_format = "`#{issue} `__" + +# Unfortunately there's no way to simply override +# tool.towncrier.type.misc.showcontent + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Miscellaneous internal changes" +showcontent = true + +[tool.mypy] +strict = true +warn_unused_configs = true +warn_unused_ignores = true +show_error_codes = true diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/setup.py b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..73713e2396e749445fe4604423eb5c5ab3c3f3ac --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +# defines __version__ +exec(open("h11/_version.py").read()) + +setup( + name="h11", + version=__version__, + description= + "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", + long_description=open("README.rst").read(), + author="Nathaniel J. Smith", + author_email="njs@pobox.com", + license="MIT", + packages=find_packages(exclude=["h11.tests"]), + package_data={'h11': ['py.typed']}, + url="https://github.com/python-hyper/h11", + python_requires=">=3.8", + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Networking", + ], +) diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/tox.ini b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6614ecf26ca9c4c4d88421a14c19539550747078 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = format, py{38, 39, 310, 311, 312, py3}, mypy + +[gh-actions] +python = + 3.8: py38, format, mypy + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + pypy-3.9: pypy3 + pypy-3.10: pypy3 + +[testenv] +deps = -r{toxinidir}/test-requirements.txt +commands = pytest --cov=h11 --cov-config=.coveragerc h11 + +[testenv:format] +basepython = python3.8 +deps = -r{toxinidir}/format-requirements.txt +commands = + black --check --diff h11/ bench/ examples/ fuzz/ + isort --check --diff --profile black --dt h11 bench examples fuzz + +[testenv:mypy] +basepython = python3.8 +deps = + mypy==1.8.0 + pytest +commands = + mypy h11/ diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/canaries/first-hunk-only.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..53547c9ed4ca16c4c5049dee5d425c8e8b626a02 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/h11/_events.py b/h11/_events.py +index c845781c9b3ab53d9e290e64d5ff7a7c3c0aad3f..ca1c3adbde2c4e7710482a18e3471f91f1da610e 100644 +--- a/h11/_events.py ++++ b/h11/_events.py +@@ -204,7 +204,7 @@ + """ + + def __post_init__(self) -> None: +- if not (100 < self.status_code <= 200): ++ if not (100 <= self.status_code < 200): + raise LocalProtocolError( + "InformationalResponse status_code should be in range " + "[100, 200), not {}".format(self.status_code) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/canaries/original-bug.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/openenv.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__btwmyz5k/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/LICENSE.source b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/LICENSE.source @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/adapter.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..d02b24ead991f33146684e723da6130f468bc817 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/adapter.json @@ -0,0 +1,135 @@ +{ + "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": "8eaf5a5d314c5d2c3a85384746ac355ab5425e56fc35deaa2bd2cd4a85aaeebb", + "gold_patch_sha256": "7e01f87eb4408fec5e516ccb2baf5f83df53907f10fb5052066f5d9496a226e9", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "bda160af36a6722533acb3be802b6a3cd34bb4b7cf3d28b856bcdd52fbb34f93", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "a3c128e95bd1c96b41943bca09d9a0dbf7b117fa744b7e01272bb84187487ab3", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/python-hyper__h11.bed0dd4a.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", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "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 test-requirements.txt" + ], + "test_dependency_source_sha256": { + "setup.py": "8120ebb8ba725a9413e97dc3e463cd4a59b2b239d461eed87faac8c5733ca56b", + "test-requirements.txt": "a289ba73acbd5364833d467558f8310d0ada06ab5bcc6ce02fcfa6c18b3aa7dc", + "tox.ini": "4c3d1968c4e49f29179f3c957b4d1856fe4b3d2c95f82aba1f78317e66d7c7d2" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "b0977e6e1dbe34224a8b9b21b06bf73dbabb877c", + "source_completion_sha256": "3aa183e29f7037c8f4eda7c9144ad2ba776d241cea68eb1a05d3de0d82575216", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__bunvpdfe", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "973d261b9b87c9aa2f37811c59bd6fc43ba20fee26e4b705890a062536982f89", + "is_fork": true, + "learner_path": "tasks/2d6c02a1c889d423b4f1160c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/b0977e6e1dbe34224a8b9b21b06bf73dbabb877c/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "458f046c81e74a9766a35464639aa631aa40311f4074936c9a98b84ad675ca90", + "provenance_path": "tasks/2d6c02a1c889d423b4f1160c/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b0977e6e1dbe34224a8b9b21b06bf73dbabb877c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6685b559451decbff2e88c3bf19a9f36b2589e74", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__bunvpdfe", + "task_sha256": "b5562757385f9f6ed4d5721e8e1cc204cdd4c3dd9aee8eee59fca8f5511900af", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "symlink_submodule_changes_supported": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__bunvpdfe", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "python-hyper/h11" +} diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/dependency-setup.sh b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e420eccd4ef84309101b05356f5b8d6e1a655654 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -r test-requirements.txt diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/environment/Dockerfile b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/instruction.md b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fe081b4f04825cdd0ebc21fcbc019e453ff5efb7 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/instruction.md @@ -0,0 +1,33 @@ +HTTP/1.0 trailer validation logic inverted + +#### Description + +When sending an EndOfMessage event to an HTTP/1.0 client, the trailer validation logic is backwards. The code currently raises an error when there are no trailers, but should raise an error when trailers are present (since HTTP/1.0 doesn't support trailers). + +#### Steps/Code to Reproduce + +```python +import h11 + +# This should work fine (no trailers for HTTP/1.0) +writer = h11._writers.Http10Writer() +try: + writer.send_eom([], lambda x: None) + print("Expected: No error") +except h11.LocalProtocolError as e: + print(f"Unexpected error: {e}") + +# This should raise an error (trailers not allowed in HTTP/1.0) +writer = h11._writers.Http10Writer() +try: + writer.send_eom([('Etag', 'asdf')], lambda x: None) + print("Unexpected: No error raised") +except h11.LocalProtocolError as e: + print(f"Expected error: {e}") +``` + +The current behavior is inverted - it raises errors when no trailers are present and allows trailers when they should be forbidden. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/metadata.json b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..4101258ffb925fdd1c74c2d91243f592babccc66 --- /dev/null +++ b/tasks/python-hyper__h11.bed0dd4a.combine_file__bunvpdfe/metadata.json @@ -0,0 +1,267 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "h11/tests/test_against_stdlib_http.py::test_h11_as_client", + "h11/tests/test_against_stdlib_http.py::test_h11_as_server", + "h11/tests/test_connection.py::test_Connection_basics_and_content_length", + "h11/tests/test_connection.py::test_chunked", + "h11/tests/test_connection.py::test_client_talking_to_http10_server", + "h11/tests/test_connection.py::test_server_talking_to_http10_client", + "h11/tests/test_connection.py::test_automatic_transfer_encoding_in_response", + "h11/tests/test_connection.py::test_automagic_connection_close_handling", + "h11/tests/test_connection.py::test_max_incomplete_event_size_countermeasure", + "h11/tests/test_connection.py::test_reuse_simple", + "h11/tests/test_connection.py::test_pipelining", + "h11/tests/test_connection.py::test_protocol_switch", + "h11/tests/test_connection.py::test_close_different_states", + "h11/tests/test_connection.py::test_pipelined_close", + "h11/tests/test_connection.py::test_sendfile", + "h11/tests/test_io.py::test_ContentLengthWriter", + "h11/tests/test_io.py::test_ChunkedWriter", + "h11/tests/test_io.py::test_Http10Writer" + ], + "PASS_TO_PASS": [ + "h11/tests/test_connection.py::test__keep_alive", + "h11/tests/test_connection.py::test__body_framing", + "h11/tests/test_connection.py::test_chunk_boundaries", + "h11/tests/test_connection.py::test_100_continue", + "h11/tests/test_connection.py::test_close_simple", + "h11/tests/test_connection.py::test_errors", + "h11/tests/test_connection.py::test_idle_receive_nothing", + "h11/tests/test_connection.py::test_connection_drop", + "h11/tests/test_connection.py::test_408_request_timeout", + "h11/tests/test_connection.py::test_empty_request", + "h11/tests/test_connection.py::test_empty_response", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_request[\\x16\\x03\\x01\\x00\\xa5]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x00]", + "h11/tests/test_connection.py::test_early_detection_of_invalid_response[\\x16\\x03\\x03\\x001]", + "h11/tests/test_connection.py::test_HEAD_framing_headers", + "h11/tests/test_connection.py::test_special_exceptions_for_lost_connection_in_message_body", + "h11/tests/test_events.py::test_events", + "h11/tests/test_events.py::test_intenum_status_code", + "h11/tests/test_events.py::test_header_casing", + "h11/tests/test_headers.py::test_normalize_and_validate", + "h11/tests/test_headers.py::test_get_set_comma_header", + "h11/tests/test_headers.py::test_has_100_continue", + "h11/tests/test_helpers.py::test_normalize_data_events", + "h11/tests/test_io.py::test_writers_simple", + "h11/tests/test_io.py::test_readers_simple", + "h11/tests/test_io.py::test_writers_unusual", + "h11/tests/test_io.py::test_readers_unusual", + "h11/tests/test_io.py::test__obsolete_line_fold_bytes", + "h11/tests/test_io.py::test_ContentLengthReader", + "h11/tests/test_io.py::test_Http10Reader", + "h11/tests/test_io.py::test_ChunkedReader", + "h11/tests/test_io.py::test_reject_garbage_after_request_line", + "h11/tests/test_io.py::test_reject_garbage_after_response_line", + "h11/tests/test_io.py::test_reject_garbage_in_header_line", + "h11/tests/test_io.py::test_reject_non_vchar_in_path", + "h11/tests/test_io.py::test_allow_some_garbage_in_cookies", + "h11/tests/test_io.py::test_host_comes_first", + "h11/tests/test_receivebuffer.py::test_receivebuffer", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_crlf_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_lf_only_delimiter]", + "h11/tests/test_receivebuffer.py::test_receivebuffer_for_invalid_delimiter[with_mixed_crlf_and_lf]", + "h11/tests/test_state.py::test_ConnectionState", + "h11/tests/test_state.py::test_ConnectionState_keep_alive", + "h11/tests/test_state.py::test_ConnectionState_keep_alive_in_DONE", + "h11/tests/test_state.py::test_ConnectionState_switch_denied", + "h11/tests/test_state.py::test_ConnectionState_protocol_switch_accepted", + "h11/tests/test_state.py::test_ConnectionState_double_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_inconsistent_protocol_switch", + "h11/tests/test_state.py::test_ConnectionState_keepalive_protocol_switch_interaction", + "h11/tests/test_state.py::test_ConnectionState_reuse", + "h11/tests/test_state.py::test_server_request_is_illegal", + "h11/tests/test_util.py::test_ProtocolError", + "h11/tests/test_util.py::test_LocalProtocolError", + "h11/tests/test_util.py::test_validate", + "h11/tests/test_util.py::test_validate_formatting", + "h11/tests/test_util.py::test_make_sentinel", + "h11/tests/test_util.py::test_bytesify" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "6685b559451decbff2e88c3bf19a9f36b2589e74", + "healthy": "1e43f0a1161922520357101c93ebde9435419fee", + "learner": "b0977e6e1dbe34224a8b9b21b06bf73dbabb877c" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE.txt", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/bench/README.rst", + "/testbed/bench/asv.conf.json", + "/testbed/bench/benchmarks/__init__.py", + "/testbed/bench/benchmarks/benchmarks.py", + "/testbed/docs/Makefile", + "/testbed/docs/requirements.txt", + "/testbed/docs/source/_examples/myclient.py", + "/testbed/docs/source/_static/closelabel.png", + "/testbed/docs/source/_static/facebox.css", + "/testbed/docs/source/_static/facebox.js", + "/testbed/docs/source/_static/loading.gif", + "/testbed/docs/source/_static/show-code.js", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/basic-usage.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/examples.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/make-state-diagrams.py", + "/testbed/docs/source/supported-http.rst", + "/testbed/examples/basic-client.py", + "/testbed/examples/trio-server.py", + "/testbed/format-requirements.txt", + "/testbed/fuzz/README.rst", + "/testbed/fuzz/afl-server-examples/1", + "/testbed/fuzz/afl-server-examples/2", + "/testbed/fuzz/afl-server-examples/3", + "/testbed/fuzz/afl-server-examples/4", + "/testbed/fuzz/afl-server.py", + "/testbed/h11/__init__.py", + "/testbed/h11/_abnf.py", + "/testbed/h11/_connection.py", + "/testbed/h11/_events.py", + "/testbed/h11/_headers.py", + "/testbed/h11/_readers.py", + "/testbed/h11/_receivebuffer.py", + "/testbed/h11/_state.py", + "/testbed/h11/_util.py", + "/testbed/h11/_version.py", + "/testbed/h11/_writers.py", + "/testbed/h11/py.typed", + "/testbed/h11/tests/__init__.py", + "/testbed/h11/tests/data/test-file", + "/testbed/h11/tests/helpers.py", + "/testbed/h11/tests/test_events.py", + "/testbed/h11/tests/test_headers.py", + "/testbed/h11/tests/test_helpers.py", + "/testbed/h11/tests/test_receivebuffer.py", + "/testbed/h11/tests/test_state.py", + "/testbed/h11/tests/test_util.py", + "/testbed/newsfragments/.gitkeep", + "/testbed/newsfragments/158.misc.rst", + "/testbed/newsfragments/README.rst", + "/testbed/notes.org", + "/testbed/pyproject.toml", + "/testbed/setup.py", + "/testbed/test-requirements.txt", + "/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": "H11Bed0dd4ae", + "profile_lines": [ + 465, + 468 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "upstream_repo": "python-hyper/h11" + }, + "original_source_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "private_test_paths": [ + "h11/tests/test_against_stdlib_http.py", + "h11/tests/test_connection.py", + "h11/tests/test_io.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": [ + "h11/_writers.py" + ], + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_stages_bytes": 1001192, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__bunvpdfe", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "python-hyper/h11" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:python-hyper__h11.bed0dd4a.combine_file__bunvpdfe", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "1e43f0a1161922520357101c93ebde9435419fee", + "instruction_sha256": "973d261b9b87c9aa2f37811c59bd6fc43ba20fee26e4b705890a062536982f89", + "is_fork": true, + "learner_path": "tasks/2d6c02a1c889d423b4f1160c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "actual_upstream_url": "https://raw.githubusercontent.com/python-hyper/h11/bed0dd4ae9774b962b19833941bb9ec4dc403da9/LICENSE.txt", + "reviewed": true, + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/python-hyper__h11.bed0dd4a/b0977e6e1dbe34224a8b9b21b06bf73dbabb877c/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": "bed0dd4ae9774b962b19833941bb9ec4dc403da9", + "patch_sha256": "458f046c81e74a9766a35464639aa631aa40311f4074936c9a98b84ad675ca90", + "provenance_path": "tasks/2d6c02a1c889d423b4f1160c/source-proof.json", + "repository_lineage": [ + "swesmith/python-hyper__h11.bed0dd4a", + "python-hyper/h11" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b0977e6e1dbe34224a8b9b21b06bf73dbabb877c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6685b559451decbff2e88c3bf19a9f36b2589e74", + "source_kind": "mutation", + "source_repo": "swesmith/python-hyper__h11.bed0dd4a", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "python-hyper__h11.bed0dd4a.combine_file__bunvpdfe", + "task_sha256": "b5562757385f9f6ed4d5721e8e1cc204cdd4c3dd9aee8eee59fca8f5511900af", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "python-hyper/h11", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +}