diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..d95651152747fa678b69a9115cec84b4e4d81553 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/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/glom/matching.py b/glom/matching.py +index c17e17ef59dcc90ffbe190c658a50dccb2fafceb..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -289,11 +289,12 @@ + + def _m_repr(self): + """should this Or() repr as M |?""" +- if isinstance(self.children[-1], (_MType, _MExpr)): +- return False +- if type(self.children[0]) in (And, Or): +- return not self.children[0]._m_repr() +- return True ++ # only used by And() and Or(), not Not(), so len(children) >= 1 ++ if isinstance(self.children[0], (_MType, _MExpr)): ++ return True ++ if type(self.children[0]) in (And, Or, Not): ++ return self.children[0]._m_repr() ++ return False + + def __repr__(self): + child_reprs = [_bool_child_repr(c) for c in self.children] +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/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g15o8zw3/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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..c2fdc07a91df61df57c6ecc2b2a34120cd60b306 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "9ff14f95989f0a8eca943e81abf51af08833ee4f8d264e57975bf96987079c55", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "abb26bf0b248738b459150e7a02eb2d0502a37fe8897c05888f6e3fc0b6c6b7c", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "bc90d5e80a4f677fafc30466d7b6331afb8c0437febeca41dac8483d991ff052", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "3e0e83c7d368693161b24324f178a71a5b30cd44", + "source_completion_sha256": "f8e68a0abdcf1982fed4b531b37e426130a0b0cabe5e45e56a2cc2ba3e54594d", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "425be46479397164b8ed15d89fba680aec63e7854af2ac8429f9d4304e208bca", + "is_fork": true, + "learner_path": "tasks/9189a3f3c7da6afadbaafbc4/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/3e0e83c7d368693161b24324f178a71a5b30cd44/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "0216e71547675fadb76f9b30a868c38b21d2b9461515313bf1ea40151c648d85", + "provenance_path": "tasks/9189a3f3c7da6afadbaafbc4/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "3e0e83c7d368693161b24324f178a71a5b30cd44", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "718a57998c6a1a55e9d20b1c1ade76b96f2c632e", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "task_sha256": "5b8a5baf1c44a3f0ca8d681d32b88ea541e6404124fe3d970599cc39926cdd7b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..380d5d27e49ca5573a8e1fe6bec2d903b2cb144d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/instruction.md @@ -0,0 +1,35 @@ +# Max and Min aggregation functions not working correctly + +I found an issue with the Max and Min aggregation functions in glom. They seem to be returning incorrect values. + +```python +>>> from glom import glom, Group, Max, Min +>>> glom([0, 1, 0], Group(Max())) +-1 # Should be 1 +>>> glom([1, 0, 1], Group(Min())) +1 # Should be 0 +``` + +The Max function seems to be returning a value that's one less than the actual maximum, and the Min function isn't returning the minimum value at all. + +Here's a simple reproduction script: + +```python +from glom import glom, Group, Max, Min + +# Test Max +data = [0, 1, 0] +result = glom(data, Group(Max())) +print(f"Max of {data}: {result}") # Prints -1 instead of 1 + +# Test Min +data = [1, 0, 1] +result = glom(data, Group(Min())) +print(f"Min of {data}: {result}") # Prints 1 instead of 0 +``` + +This is breaking any code that relies on these aggregation functions to return the actual maximum and minimum values. + +## 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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..ee53ced413ab869422fba64039f3cb3343692b30 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "718a57998c6a1a55e9d20b1c1ade76b96f2c632e", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "3e0e83c7d368693161b24324f178a71a5b30cd44" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_grouping.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": [ + "glom/grouping.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1424840, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "425be46479397164b8ed15d89fba680aec63e7854af2ac8429f9d4304e208bca", + "is_fork": true, + "learner_path": "tasks/9189a3f3c7da6afadbaafbc4/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/3e0e83c7d368693161b24324f178a71a5b30cd44/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "0216e71547675fadb76f9b30a868c38b21d2b9461515313bf1ea40151c648d85", + "provenance_path": "tasks/9189a3f3c7da6afadbaafbc4/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "3e0e83c7d368693161b24324f178a71a5b30cd44", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "718a57998c6a1a55e9d20b1c1ade76b96f2c632e", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "task_sha256": "5b8a5baf1c44a3f0ca8d681d32b88ea541e6404124fe3d970599cc39926cdd7b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ae783ce9032ee2a9f562259a1c70e22d2528091b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "9ff14f95989f0a8eca943e81abf51af08833ee4f8d264e57975bf96987079c55", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/3e0e83c7d368693161b24324f178a71a5b30cd44/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "f8e68a0abdcf1982fed4b531b37e426130a0b0cabe5e45e56a2cc2ba3e54594d", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "e38c96d5a3783843f4e5d189ce8d23be8d9a98acac76ffc60d7f218355490747", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "425be46479397164b8ed15d89fba680aec63e7854af2ac8429f9d4304e208bca", + "is_fork": true, + "learner_path": "tasks/9189a3f3c7da6afadbaafbc4/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/3e0e83c7d368693161b24324f178a71a5b30cd44/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "0216e71547675fadb76f9b30a868c38b21d2b9461515313bf1ea40151c648d85", + "provenance_path": "tasks/9189a3f3c7da6afadbaafbc4/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "3e0e83c7d368693161b24324f178a71a5b30cd44", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "718a57998c6a1a55e9d20b1c1ade76b96f2c632e", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__g5ew8sro", + "task_sha256": "5b8a5baf1c44a3f0ca8d681d32b88ea541e6404124fe3d970599cc39926cdd7b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..61f2f3abcbb55a49886aa46a33fe035dd0caad94 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/provided-gold.diff @@ -0,0 +1,27 @@ +diff --git a/glom/grouping.py b/glom/grouping.py +index a2b07d664dd102c9b25f3942e1011becd7c0b582..122bd0863df47161b8eb663797705f4c3e00a4ab 100644 +--- a/glom/grouping.py ++++ b/glom/grouping.py +@@ -209,8 +209,8 @@ + __slots__ = () + + def agg(self, target, tree): +- if self not in tree or target < tree[self]: +- tree[self] = target - 1 ++ if self not in tree or target > tree[self]: ++ tree[self] = target + return tree[self] + + def __repr__(self): +@@ -228,9 +228,9 @@ + __slots__ = () + + def agg(self, target, tree): +- if self not in tree or target <= tree[self]: ++ if self not in tree or target < tree[self]: + tree[self] = target +- return target ++ return tree[self] + + def __repr__(self): + return '%s()' % self.__class__.__name__ diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..43e5b09cb3888d714ad45059f7c430c5c0dd06f4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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/glom/grouping.py b/glom/grouping.py +index a2b07d664dd102c9b25f3942e1011becd7c0b582..122bd0863df47161b8eb663797705f4c3e00a4ab 100644 +--- a/glom/grouping.py ++++ b/glom/grouping.py +@@ -209,8 +209,8 @@ + __slots__ = () + + def agg(self, target, tree): +- if self not in tree or target < tree[self]: +- tree[self] = target - 1 ++ if self not in tree or target > tree[self]: ++ tree[self] = target + return tree[self] + + def __repr__(self): +@@ -228,9 +228,9 @@ + __slots__ = () + + def agg(self, target, tree): +- if self not in tree or target <= tree[self]: ++ if self not in tree or target < tree[self]: + tree[self] = target +- return target ++ return tree[self] + + def __repr__(self): + return '%s()' % self.__class__.__name__ +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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a898b71e99bedf8c1d4983a8c1365c9f9a08fb3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ae0d3787e6a25023a58c65371ed124b629126739712f46760068e5f80d38ba36" +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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..80b063fab854d389214c3feda5917fb28f2c8827 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b8396142858c8fe435568f1de1c5420db2f893a --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/canaries/first-hunk-only.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/glom/grouping.py b/glom/grouping.py +index a2b07d664dd102c9b25f3942e1011becd7c0b582..122bd0863df47161b8eb663797705f4c3e00a4ab 100644 +--- a/glom/grouping.py ++++ b/glom/grouping.py +@@ -209,8 +209,8 @@ + __slots__ = () + + def agg(self, target, tree): +- if self not in tree or target < tree[self]: +- tree[self] = target - 1 ++ if self not in tree or target > tree[self]: ++ tree[self] = target + return tree[self] + + def __repr__(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/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__g5ew8sro/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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f02b4262e91e9faf5a158449cb94174c338573fd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "e15699a165c5e374187bac80ac1a3855d1b0b87a0b057a58d42fa207d0becaf4", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "bb6ce81fe6dc77904968539352c5028bd4e640cfbdbb99d1eecd62d1e802d895", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "e764720f2ad76369eb726265c7d44323dc2434c36319696fa44d7e166d41654b", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "b2db807c5365454b88d014839322e2d3cb1c31e0", + "source_completion_sha256": "a8e9b5c6ae6f2b0549af9a195b2ea8a8e4fff976826a7ab48d40951cbc150b49", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "641c6aa95950384096ecd2e09046024a33a497e0a4946a4ec5260fa1bd4d8dfd", + "is_fork": true, + "learner_path": "tasks/1314716114e1b2479980b42c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b2db807c5365454b88d014839322e2d3cb1c31e0/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "21bbaab26250c048820d9b5151b3b4645f58193b0d24d74639115d3c9a4c2d5e", + "provenance_path": "tasks/1314716114e1b2479980b42c/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b2db807c5365454b88d014839322e2d3cb1c31e0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a99fa60a540ed8f10b1661fa031965e0bf4c6113", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "task_sha256": "3ac296ba5d4a7ab622f854196bde1f1c230181389475ee3f9ecd14f6fe477b1a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..da1b8a79d5a53a667f80ea4131fcedefb6bd30ad --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/instruction.md @@ -0,0 +1,39 @@ +CLI returns early without processing glom operations + +#### Description + +The glom CLI is returning early from the `glom_cli` function without actually executing the glom operation, causing it to output nothing instead of the expected results. + +#### Steps/Code to Reproduce + +```python +import glom.cli as cli + +# This should return 0 and process the glom operation +argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] +result = cli.main(argv) +print(f"Return code: {result}") # Expected: 0, Actual: None + +# This should return 1 due to failed glom operation +argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] +result = cli.main(argv) +print(f"Return code: {result}") # Expected: 1, Actual: None +``` + +Or using the command line directly: + +```bash +# Should output: "d" +echo '{"a": {"b": {"c": "d"}}}' | python -m glom a.b.c +# Actual output: (nothing) + +# Should output formatted JSON +python -m glom --indent 0 a.b.c '{"a": {"b": {"c": "d"}}}' +# Actual output: (nothing) +``` + +The CLI appears to be exiting early without processing the glom specification against the target data, and is not returning proper exit codes. + +## 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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..100a697a64bf62e5dd36707245211ade1b437a93 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "a99fa60a540ed8f10b1661fa031965e0bf4c6113", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "b2db807c5365454b88d014839322e2d3cb1c31e0" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_cli.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": [ + "glom/cli.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1421922, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "641c6aa95950384096ecd2e09046024a33a497e0a4946a4ec5260fa1bd4d8dfd", + "is_fork": true, + "learner_path": "tasks/1314716114e1b2479980b42c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b2db807c5365454b88d014839322e2d3cb1c31e0/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "21bbaab26250c048820d9b5151b3b4645f58193b0d24d74639115d3c9a4c2d5e", + "provenance_path": "tasks/1314716114e1b2479980b42c/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b2db807c5365454b88d014839322e2d3cb1c31e0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a99fa60a540ed8f10b1661fa031965e0bf4c6113", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "task_sha256": "3ac296ba5d4a7ab622f854196bde1f1c230181389475ee3f9ecd14f6fe477b1a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..9682a668c4b89fbfba2e99c04fba20fa3b82c2b1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "e15699a165c5e374187bac80ac1a3855d1b0b87a0b057a58d42fa207d0becaf4", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b2db807c5365454b88d014839322e2d3cb1c31e0/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "a8e9b5c6ae6f2b0549af9a195b2ea8a8e4fff976826a7ab48d40951cbc150b49", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "5627c235e957f36610a97072b9bab767aeeca9f3c887e5f0fc3e82a13da798b7", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "641c6aa95950384096ecd2e09046024a33a497e0a4946a4ec5260fa1bd4d8dfd", + "is_fork": true, + "learner_path": "tasks/1314716114e1b2479980b42c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b2db807c5365454b88d014839322e2d3cb1c31e0/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "21bbaab26250c048820d9b5151b3b4645f58193b0d24d74639115d3c9a4c2d5e", + "provenance_path": "tasks/1314716114e1b2479980b42c/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b2db807c5365454b88d014839322e2d3cb1c31e0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a99fa60a540ed8f10b1661fa031965e0bf4c6113", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__izanr69t", + "task_sha256": "3ac296ba5d4a7ab622f854196bde1f1c230181389475ee3f9ecd14f6fe477b1a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a349a3fb70cfd88bb777da594b8f1a9b8fb27bda --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/provided-gold.diff @@ -0,0 +1,74 @@ +diff --git a/glom/cli.py b/glom/cli.py +index beacb26c0bf52c9ca518bd943496f826ca3e6b44..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -50,9 +50,9 @@ + # TODO: --default? + + def glom_cli(target, spec, indent, debug, inspect, scalar): +- +- if not indent: +- indent = None ++ """Command-line interface to the glom library, providing nested data ++ access and data restructuring with the power of Python. ++ """ + if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +@@ -60,21 +60,22 @@ + recursive=inspect, + breakpoint=inspect and stdin_open, + post_mortem=debug and stdin_open) +- """Command-line interface to the glom library, providing nested data +- access and data restructuring with the power of Python. +- """ +- return ++ ++ try: ++ result = glom.glom(target, spec) ++ except GlomError as ge: ++ print(f'{ge.__class__.__name__}: {ge}') ++ return 1 ++ ++ if not indent: ++ indent = None + + if scalar and is_scalar(result): + print(result, end='') + else: + print(json.dumps(result, indent=indent, sort_keys=True)) +- +- try: +- result = glom.glom(target, spec) +- except GlomError as ge: +- print(f'{ge.__class__.__name__}: {ge}') +- return 1 ++ return ++ + + def get_command(): + posargs = PosArgSpec(str, max_count=2, display={'label': '[spec [target]]'}) +@@ -99,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): +@@ -230,11 +231,11 @@ + + + def _compile_code(code_str, name, env=None, verbose=False): ++ code = compile(code_str, '', 'single') + if verbose: + print(code_str) + if env is None: + env = {} +- code = compile(code_str, '', 'single') ++ exec(code, env) + + return env[name] +- exec(code, env) +\ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..dad3a517ea20dbe814506722ab5b8c3053c55920 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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/glom/cli.py b/glom/cli.py +index beacb26c0bf52c9ca518bd943496f826ca3e6b44..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -50,9 +50,9 @@ + # TODO: --default? + + def glom_cli(target, spec, indent, debug, inspect, scalar): +- +- if not indent: +- indent = None ++ """Command-line interface to the glom library, providing nested data ++ access and data restructuring with the power of Python. ++ """ + if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +@@ -60,21 +60,22 @@ + recursive=inspect, + breakpoint=inspect and stdin_open, + post_mortem=debug and stdin_open) +- """Command-line interface to the glom library, providing nested data +- access and data restructuring with the power of Python. +- """ +- return ++ ++ try: ++ result = glom.glom(target, spec) ++ except GlomError as ge: ++ print(f'{ge.__class__.__name__}: {ge}') ++ return 1 ++ ++ if not indent: ++ indent = None + + if scalar and is_scalar(result): + print(result, end='') + else: + print(json.dumps(result, indent=indent, sort_keys=True)) +- +- try: +- result = glom.glom(target, spec) +- except GlomError as ge: +- print(f'{ge.__class__.__name__}: {ge}') +- return 1 ++ return ++ + + def get_command(): + posargs = PosArgSpec(str, max_count=2, display={'label': '[spec [target]]'}) +@@ -99,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): +@@ -230,11 +231,11 @@ + + + def _compile_code(code_str, name, env=None, verbose=False): ++ code = compile(code_str, '', 'single') + if verbose: + print(code_str) + if env is None: + env = {} +- code = compile(code_str, '', 'single') ++ exec(code, env) + + return env[name] +- exec(code, env) +\ No newline at end of file +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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..19347ce733897f3b5198f42371b7bd7a91648a3e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:24007fa57d61f55bcdf0541ab632334bec446d5c474d8ae621b5838ce4515a09" +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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..722d9cb7efca1e0d21312e632c2c2ec9849dea5c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..0207a32482ae63c5595414e11b34fe39701c7b64 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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/glom/cli.py b/glom/cli.py +index beacb26c0bf52c9ca518bd943496f826ca3e6b44..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -50,9 +50,9 @@ + # TODO: --default? + + def glom_cli(target, spec, indent, debug, inspect, scalar): +- +- if not indent: +- indent = None ++ """Command-line interface to the glom library, providing nested data ++ access and data restructuring with the power of Python. ++ """ + if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +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/mahmoud__glom.fb3c4e76.combine_file__izanr69t/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__izanr69t/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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..8e43a481ac47234a8275e19e85590dc17d636488 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "633c23c74ee354832fb87b618b5ea9553d0900f61d49f0fb161247ce58d46fee", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "8b8b67db50c86a806833f12be14066dd8e1c182fb9c80ec11104f9046d470c02", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "4fd934cd933db671560e387d9e082ea3e13349abec63ee8e59959fb6d3f649d8", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "db5ff76e2ab0b680357ba636a21f44310809fb6b", + "source_completion_sha256": "4e1f1c294d442c6014401cb1eb41b3842ef25548cb461a37d6db3c03e48cd757", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "17e3b01689e25d1330fe6e68a49b6f22320577e12207578f3df3716575a87e80", + "is_fork": true, + "learner_path": "tasks/b1afc4688fce4ab4d8c03835/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/db5ff76e2ab0b680357ba636a21f44310809fb6b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "ad8af4f44aaf44d267115d4f8370591f45e58ac3a3970a1331f35d72ddad05de", + "provenance_path": "tasks/b1afc4688fce4ab4d8c03835/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "db5ff76e2ab0b680357ba636a21f44310809fb6b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "799025e83fdb125ac396744fdb23124d4dc7ddfb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "task_sha256": "ea68198471ee995c9d17e51c55cd910a15764f7b776934fc52f9cf62d41a0fec", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57d200b193ad9623774abb10addc0a0b6c4d9f79 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/instruction.md @@ -0,0 +1,31 @@ +Assign and Delete operations produce incorrect results with sequence items + +#### Description + +When using Assign or Delete operations on sequence items (lists, tuples), the operations are producing incorrect results. Specifically, when assigning values to sequence indices, the values are being negated, and when deleting from sequences, the operations are not working as expected. + +#### Steps/Code to Reproduce + +```python +from glom import glom, Assign, Delete, T + +# Assignment issue - values get negated +target = {'alist': [0, 1, 2]} +result = glom(target, Assign('alist.2', 5)) +print(f"Expected: {{'alist': [0, 1, 5]}}") +print(f"Actual: {result}") + +# Delete issue - operations don't work correctly +target2 = {'alist': [0, 1, 2]} +result2 = glom(target2, Delete('alist.1')) +print(f"Expected: {{'alist': [0, 2]}}") +print(f"Actual: {result2}") +``` + +The assignment operation should set `target['alist'][2] = 5` but instead it's setting `target['alist'][2] = -5`. Similarly, delete operations on sequence items are not functioning properly. + +This affects any glom operations that modify sequence elements through indexing, making it impossible to reliably mutate lists and other sequences. + +## 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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9c5f840afa27bd00cb4966f2eefd1844eb6ee236 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_star_broadcast" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "799025e83fdb125ac396744fdb23124d4dc7ddfb", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "db5ff76e2ab0b680357ba636a21f44310809fb6b" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_error.py", + "glom/test/test_mutation.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": [ + "glom/mutation.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1401113, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "17e3b01689e25d1330fe6e68a49b6f22320577e12207578f3df3716575a87e80", + "is_fork": true, + "learner_path": "tasks/b1afc4688fce4ab4d8c03835/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/db5ff76e2ab0b680357ba636a21f44310809fb6b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "ad8af4f44aaf44d267115d4f8370591f45e58ac3a3970a1331f35d72ddad05de", + "provenance_path": "tasks/b1afc4688fce4ab4d8c03835/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "db5ff76e2ab0b680357ba636a21f44310809fb6b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "799025e83fdb125ac396744fdb23124d4dc7ddfb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "task_sha256": "ea68198471ee995c9d17e51c55cd910a15764f7b776934fc52f9cf62d41a0fec", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..34db5941b6a30e1e636d7a0bc8fc0130dd77e8bd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "633c23c74ee354832fb87b618b5ea9553d0900f61d49f0fb161247ce58d46fee", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/db5ff76e2ab0b680357ba636a21f44310809fb6b/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "4e1f1c294d442c6014401cb1eb41b3842ef25548cb461a37d6db3c03e48cd757", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "4127df12ea3c4556203504c9f000264eaffdf20a51fb43da6b48ef9e6a55c162", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "17e3b01689e25d1330fe6e68a49b6f22320577e12207578f3df3716575a87e80", + "is_fork": true, + "learner_path": "tasks/b1afc4688fce4ab4d8c03835/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/db5ff76e2ab0b680357ba636a21f44310809fb6b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "ad8af4f44aaf44d267115d4f8370591f45e58ac3a3970a1331f35d72ddad05de", + "provenance_path": "tasks/b1afc4688fce4ab4d8c03835/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "db5ff76e2ab0b680357ba636a21f44310809fb6b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "799025e83fdb125ac396744fdb23124d4dc7ddfb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c", + "task_sha256": "ea68198471ee995c9d17e51c55cd910a15764f7b776934fc52f9cf62d41a0fec", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..41666a7c2c44a879ca8c6d77d4772df1c7a309b5 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/provided-gold.diff @@ -0,0 +1,31 @@ +diff --git a/glom/mutation.py b/glom/mutation.py +index 44f4d1188adddb173839ff0fec4eee5091f151f0..c3fc322efb41f3f1a653d66eb364cd6690c7e6a5 100644 +--- a/glom/mutation.py ++++ b/glom/mutation.py +@@ -49,13 +49,13 @@ + + def _apply_for_each(func, path, val): + layers = path.path_t.__stars__() +- if layers > 1: +- for i in range(layers): +- val = sum(val, []) # apply flatten one extra time ++ if layers: ++ for i in range(layers - 1): ++ val = sum(val, []) # flatten out the extra layers + for inner in val: + func(inner) + else: +- pass # swallow the function call on val when layers are zero ++ func(val) + + + class Assign: +@@ -213,7 +213,7 @@ + + + def _set_sequence_item(target, idx, val): +- target[int(idx)] = -val ++ target[int(idx)] = val + + + def _assign_autodiscover(type_obj): diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9c7535bc62490ec23516ceccec0e4245c084d0ae --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/solution/solve.sh @@ -0,0 +1,37 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/mutation.py b/glom/mutation.py +index 44f4d1188adddb173839ff0fec4eee5091f151f0..c3fc322efb41f3f1a653d66eb364cd6690c7e6a5 100644 +--- a/glom/mutation.py ++++ b/glom/mutation.py +@@ -49,13 +49,13 @@ + + def _apply_for_each(func, path, val): + layers = path.path_t.__stars__() +- if layers > 1: +- for i in range(layers): +- val = sum(val, []) # apply flatten one extra time ++ if layers: ++ for i in range(layers - 1): ++ val = sum(val, []) # flatten out the extra layers + for inner in val: + func(inner) + else: +- pass # swallow the function call on val when layers are zero ++ func(val) + + + class Assign: +@@ -213,7 +213,7 @@ + + + def _set_sequence_item(target, idx, val): +- target[int(idx)] = -val ++ target[int(idx)] = val + + + def _assign_autodiscover(type_obj): +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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c76c152af1b3b962f117fec88c6b210daaca9b18 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:10721cf5787122ba7a8c8514c7e0bf6845b0100f8d1a9a997db29c85bed47c17" +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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..9446aab5c5f427b62a904e15d77ce6bcb138f4cd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_star_broadcast" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d0cf2eb26bfd53abc7d0a936bced04b36d214b8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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/glom/mutation.py b/glom/mutation.py +index 44f4d1188adddb173839ff0fec4eee5091f151f0..c3fc322efb41f3f1a653d66eb364cd6690c7e6a5 100644 +--- a/glom/mutation.py ++++ b/glom/mutation.py +@@ -49,13 +49,13 @@ + + def _apply_for_each(func, path, val): + layers = path.path_t.__stars__() +- if layers > 1: +- for i in range(layers): +- val = sum(val, []) # apply flatten one extra time ++ if layers: ++ for i in range(layers - 1): ++ val = sum(val, []) # flatten out the extra layers + for inner in val: + func(inner) + else: +- pass # swallow the function call on val when layers are zero ++ func(val) + + + class Assign: +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/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__j7ca9n5c/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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..550c2443e46dd2d572b7ce91dcc9cc5ab52558c3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "e1cb22064483844323e116d272b51cca8d448c38c621b92f634ff34c0cc8c379", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "8a16218f6e104d6d278fcde219a56cbb1c60200b988e7c20b882c4f57a8afa14", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "50d38851a96b260cebd381be0c485ed0aeeffeb3657598cee048e5faff2945c1", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "b54eba65318c9835dc5d9d6571dbcd539b735105", + "source_completion_sha256": "ec2c7beb5dd4913a11f13c5270db2f197c224f2cc808a09753f8e3a6995a3f8a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "e4e2a1e57e0b2cc334ed54d45d55127d4904f0adf41545eb9af2b4d442551ad2", + "is_fork": true, + "learner_path": "tasks/fcfa9622331796471e5804f0/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b54eba65318c9835dc5d9d6571dbcd539b735105/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "053d8415e5708daf3145b207dd2f258abe7e1ad2c6e9d8c66a8309cfd6e0f632", + "provenance_path": "tasks/fcfa9622331796471e5804f0/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b54eba65318c9835dc5d9d6571dbcd539b735105", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "557e6b4ca334cd53266f7683c0636ae47ea41ad3", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "task_sha256": "d1e603e22c480e29bdd7b2df1e758f17b251dd9419ef1600b2c994049c8eb171", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1910a82aa861c66b7856e647b1ba9903972b8f7e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/instruction.md @@ -0,0 +1,36 @@ +T and S path evaluation broken after recent changes + +#### Description + +Something seems to have broken the core path evaluation logic for T (target) and S (scope) operations. Basic glom operations that were working before are now failing with IndexError exceptions. + +#### Steps/Code to Reproduce + +```python +from glom import glom, T + +# Simple target access fails +data = {'a': {'b': 'value'}} +result = glom(data, 'a.b') # Should return 'value' +``` + +```python +from glom import glom, T + +# T path access fails +data = {'name': 'test'} +result = glom(data, T['name']) # Should return 'test' +``` + +```python +from glom import glom, S + +# Scope operations fail +result = glom({}, S.some_var) # Should handle scope access +``` + +All of these basic operations are now raising `IndexError: list index out of range` when they should work normally. The issue appears to affect most glom functionality including basic path access, T/S operations, and assignment operations. + +## 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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..3a5be57752e469d749a7a4255a7bcd110d70fa46 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_tutorial.py::test_tutorial" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_fallback", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "557e6b4ca334cd53266f7683c0636ae47ea41ad3", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "b54eba65318c9835dc5d9d6571dbcd539b735105" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_basic.py", + "glom/test/test_check.py", + "glom/test/test_cli.py", + "glom/test/test_error.py", + "glom/test/test_fill.py", + "glom/test/test_grouping.py", + "glom/test/test_match.py", + "glom/test/test_mutation.py", + "glom/test/test_path_and_t.py", + "glom/test/test_reduction.py", + "glom/test/test_scope_vars.py", + "glom/test/test_spec.py", + "glom/test/test_streaming.py", + "glom/test/test_target_types.py", + "glom/test/test_tutorial.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": [ + "glom/core.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1323353, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "e4e2a1e57e0b2cc334ed54d45d55127d4904f0adf41545eb9af2b4d442551ad2", + "is_fork": true, + "learner_path": "tasks/fcfa9622331796471e5804f0/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b54eba65318c9835dc5d9d6571dbcd539b735105/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "053d8415e5708daf3145b207dd2f258abe7e1ad2c6e9d8c66a8309cfd6e0f632", + "provenance_path": "tasks/fcfa9622331796471e5804f0/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b54eba65318c9835dc5d9d6571dbcd539b735105", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "557e6b4ca334cd53266f7683c0636ae47ea41ad3", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "task_sha256": "d1e603e22c480e29bdd7b2df1e758f17b251dd9419ef1600b2c994049c8eb171", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..7b76a84f0a841d018072d241fa61d21af36704d6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "e1cb22064483844323e116d272b51cca8d448c38c621b92f634ff34c0cc8c379", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b54eba65318c9835dc5d9d6571dbcd539b735105/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "ec2c7beb5dd4913a11f13c5270db2f197c224f2cc808a09753f8e3a6995a3f8a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "0110fa32437e61d1369055652c22c545c5271602755913fb5ad13dff642c7970", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "e4e2a1e57e0b2cc334ed54d45d55127d4904f0adf41545eb9af2b4d442551ad2", + "is_fork": true, + "learner_path": "tasks/fcfa9622331796471e5804f0/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/b54eba65318c9835dc5d9d6571dbcd539b735105/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "053d8415e5708daf3145b207dd2f258abe7e1ad2c6e9d8c66a8309cfd6e0f632", + "provenance_path": "tasks/fcfa9622331796471e5804f0/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b54eba65318c9835dc5d9d6571dbcd539b735105", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "557e6b4ca334cd53266f7683c0636ae47ea41ad3", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__myb75dj6", + "task_sha256": "d1e603e22c480e29bdd7b2df1e758f17b251dd9419ef1600b2c994049c8eb171", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..086a50af20751fc91b48b9095d2449b5ee3ba29d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/provided-gold.diff @@ -0,0 +1,219 @@ +diff --git a/glom/core.py b/glom/core.py +index 6728907d4c636efeb028f33f269053088f108736..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -148,17 +148,22 @@ + self.__wrapped = exc + + def _finalize(self, scope): ++ # careful when changing how this functionality works; pytest seems to mess with ++ # the traceback module or sys.exc_info(). we saw different stacks when originally ++ # developing this in June 2020. + etype, evalue, _ = sys.exc_info() + tb_lines = traceback.format_exc().strip().splitlines() + limit = 0 +- for line in tb_lines: # Reversed logic in for loop ++ for line in reversed(tb_lines): + if _PKG_DIR_PATH in line: +- limit += 1 # Changed decrement to increment ++ limit -= 1 + break +- limit -= 1 # Changed increment to decrement +- self._tb_lines = tb_lines[:-limit] # Changed slicing to remove wrong lines +- if set(self._tb_lines[-1]) <= {' ', '^', '~'}: # Used last line instead of the first +- self._tb_lines = self._tb_lines[:-1] # Remove the last line ++ limit += 1 ++ self._tb_lines = tb_lines[-limit:] ++ # if the first line is trying to put a caret at a byte-code location on a line that ++ # isn't being displayed, skip it ++ if set(self._tb_lines[0]) <= {' ', '^', '~'}: ++ self._tb_lines = self._tb_lines[1:] + self._scope = scope + + def __str__(self): +@@ -1501,7 +1506,7 @@ + return tuple(({T: 'T', S: 'S', A: 'A'}[t_path[0]],) + t_path[1:]) + + def __setstate__(self, state): +- self.__ops__ = ({'T': S, 'S': T, 'A': A}[state[0]],) + state[1:] ++ self.__ops__ = ({'T': T, 'S': S, 'A': A}[state[0]],) + state[1:] + + + def _t_child(parent, operation, arg): +@@ -1524,117 +1529,130 @@ + try: + cur = scope[key] + except KeyError as e: +- err = PathAccessError(e, Path(_t), 1) # always only one level depth, hence 0 ++ err = PathAccessError(e, Path(_t), 0) # always only one level depth, hence 0 + if err: +- pass # silently swallow the error without raising +- return None ++ raise err ++ return cur + + + def _t_eval(target, _t, scope): + t_path = _t.__ops__ +- i = 0 ++ i = 1 + fetch_till = len(t_path) + root = t_path[0] + if root is T: ++ cur = target ++ elif root is S or root is A: ++ # A is basically the same as S, but last step is assign ++ if root is A: ++ fetch_till -= 2 ++ if fetch_till < 1: ++ raise BadSpec('cannot assign without destination') + cur = scope +- elif root is A or root is S: +- if root is S: +- fetch_till -= 1 +- if fetch_till < 1: +- pass +- cur = target +- if fetch_till > 1 and t_path[1] in ('P', '.'): +- cur = _s_first_magic(scope, t_path[2], _t) +- i += 1 +- elif root is A and fetch_till > 1 and t_path[1] == '(': ++ if fetch_till > 1 and t_path[1] in ('.', 'P'): ++ cur = _s_first_magic(cur, t_path[2], _t) ++ i += 2 ++ elif root is S and fetch_till > 1 and t_path[1] == '(': ++ # S(var='spec') style assignment + _, kwargs = t_path[2] +- target.update({ +- k: arg_val(scope, v, target) for k, v in kwargs.items()}) +- return scope ++ scope.update({ ++ k: arg_val(target, v, scope) for k, v in kwargs.items()}) ++ return target + + else: +- raise ValueError('TType instance with invalid root') ++ raise ValueError('TType instance with invalid root') # pragma: no cover + pae = None + while i < fetch_till: + op, arg = t_path[i], t_path[i + 1] +- arg = arg_val(cur, arg, scope) +- if op == '[': ++ arg = arg_val(target, arg, scope) ++ if op == '.': + try: + cur = getattr(cur, arg) + except AttributeError as e: + pae = PathAccessError(e, Path(_t), i // 2) +- elif op == '.': ++ elif op == '[': + try: + cur = cur[arg] + except (KeyError, IndexError, TypeError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op == 'P': ++ # Path type stuff (fuzzy match) + get = scope[TargetRegistry].get_handler('get', cur, path=t_path[2:i+2:2]) + try: +- cur = get(scope, arg) ++ cur = get(cur, arg) + except Exception as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op in 'xX': + nxt = [] + get_handler = scope[TargetRegistry].get_handler +- if op == 'X': ++ if op == 'x': # increases arity of cur each time through ++ # TODO: so many try/except -- could scope[TargetRegistry] stuff be cached on type? + _extend_children(nxt, cur, get_handler) +- elif op == 'x': ++ elif op == 'X': + sofar = set() + _extend_children(nxt, cur, get_handler) + for item in nxt: + if id(item) not in sofar: ++ sofar.add(id(item)) + _extend_children(nxt, item, get_handler) +- sofar.add(id(item)) ++ nxt.insert(0, cur) ++ # handle the rest of the t_path in recursive calls + cur = [] + todo = TType() + todo.__ops__ = (root,) + t_path[i+2:] + for child in nxt: + try: +- cur.append(_t_eval(todo, child, scope)) ++ cur.append(_t_eval(child, todo, scope)) + except PathAccessError: + pass +- continue ++ break # we handled the rest in recursive call, break loop + elif op == '(': + args, kwargs = arg + scope[Path] += t_path[2:i+2:2] + cur = scope[glom]( +- target, Call(cur, kwargs, args), scope) +- else: ++ target, Call(cur, args, kwargs), scope) ++ # call with target rather than cur, ++ # because it is probably more intuitive ++ # if args to the call "reset" their path ++ # e.g. "T.a" should mean the same thing ++ # in both of these specs: T.a and T.b(T.a) ++ else: # arithmetic operators + try: +- if op == '-': ++ if op == '+': + cur = cur + arg +- elif op == '+': ++ elif op == '-': ++ cur = cur - arg ++ elif op == '*': + cur = cur * arg +- elif op == '//': +- cur = cur - arg ++ #elif op == '#': ++ # cur = cur // arg # TODO: python 2 friendly approach? + elif op == '/': + cur = cur / arg + elif op == '%': +- cur = cur // arg ++ cur = cur % arg + elif op == ':': + cur = cur ** arg + elif op == '&': ++ cur = cur & arg ++ elif op == '|': ++ cur = cur | arg ++ elif op == '^': + cur = cur ^ arg +- elif op == '|': +- cur = cur & arg +- elif op == '^': +- cur = cur | arg + elif op == '~': + cur = ~cur + elif op == '_': + cur = -cur +- except (ZeroDivisionError, TypeError) as e: ++ except (TypeError, ZeroDivisionError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + if pae: +- return scope +- i += 1 +- if root is not A: ++ raise pae ++ i += 2 ++ if root is A: + op, arg = t_path[-2:] +- if cur is target: +- op = '[' +- _assign_op(dest=cur, op=op, arg=arg, val=scope, path=_t, scope=target) +- return scope ++ if cur is scope: ++ op = '[' # all assignment on scope is setitem ++ _assign_op(dest=cur, op=op, arg=arg, val=target, path=_t, scope=scope) ++ return target # A should not change the target + return cur + + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe5b8d11314796df0fe3532e35bc3c87464db5f9 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/solution/solve.sh @@ -0,0 +1,225 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/core.py b/glom/core.py +index 6728907d4c636efeb028f33f269053088f108736..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -148,17 +148,22 @@ + self.__wrapped = exc + + def _finalize(self, scope): ++ # careful when changing how this functionality works; pytest seems to mess with ++ # the traceback module or sys.exc_info(). we saw different stacks when originally ++ # developing this in June 2020. + etype, evalue, _ = sys.exc_info() + tb_lines = traceback.format_exc().strip().splitlines() + limit = 0 +- for line in tb_lines: # Reversed logic in for loop ++ for line in reversed(tb_lines): + if _PKG_DIR_PATH in line: +- limit += 1 # Changed decrement to increment ++ limit -= 1 + break +- limit -= 1 # Changed increment to decrement +- self._tb_lines = tb_lines[:-limit] # Changed slicing to remove wrong lines +- if set(self._tb_lines[-1]) <= {' ', '^', '~'}: # Used last line instead of the first +- self._tb_lines = self._tb_lines[:-1] # Remove the last line ++ limit += 1 ++ self._tb_lines = tb_lines[-limit:] ++ # if the first line is trying to put a caret at a byte-code location on a line that ++ # isn't being displayed, skip it ++ if set(self._tb_lines[0]) <= {' ', '^', '~'}: ++ self._tb_lines = self._tb_lines[1:] + self._scope = scope + + def __str__(self): +@@ -1501,7 +1506,7 @@ + return tuple(({T: 'T', S: 'S', A: 'A'}[t_path[0]],) + t_path[1:]) + + def __setstate__(self, state): +- self.__ops__ = ({'T': S, 'S': T, 'A': A}[state[0]],) + state[1:] ++ self.__ops__ = ({'T': T, 'S': S, 'A': A}[state[0]],) + state[1:] + + + def _t_child(parent, operation, arg): +@@ -1524,117 +1529,130 @@ + try: + cur = scope[key] + except KeyError as e: +- err = PathAccessError(e, Path(_t), 1) # always only one level depth, hence 0 ++ err = PathAccessError(e, Path(_t), 0) # always only one level depth, hence 0 + if err: +- pass # silently swallow the error without raising +- return None ++ raise err ++ return cur + + + def _t_eval(target, _t, scope): + t_path = _t.__ops__ +- i = 0 ++ i = 1 + fetch_till = len(t_path) + root = t_path[0] + if root is T: ++ cur = target ++ elif root is S or root is A: ++ # A is basically the same as S, but last step is assign ++ if root is A: ++ fetch_till -= 2 ++ if fetch_till < 1: ++ raise BadSpec('cannot assign without destination') + cur = scope +- elif root is A or root is S: +- if root is S: +- fetch_till -= 1 +- if fetch_till < 1: +- pass +- cur = target +- if fetch_till > 1 and t_path[1] in ('P', '.'): +- cur = _s_first_magic(scope, t_path[2], _t) +- i += 1 +- elif root is A and fetch_till > 1 and t_path[1] == '(': ++ if fetch_till > 1 and t_path[1] in ('.', 'P'): ++ cur = _s_first_magic(cur, t_path[2], _t) ++ i += 2 ++ elif root is S and fetch_till > 1 and t_path[1] == '(': ++ # S(var='spec') style assignment + _, kwargs = t_path[2] +- target.update({ +- k: arg_val(scope, v, target) for k, v in kwargs.items()}) +- return scope ++ scope.update({ ++ k: arg_val(target, v, scope) for k, v in kwargs.items()}) ++ return target + + else: +- raise ValueError('TType instance with invalid root') ++ raise ValueError('TType instance with invalid root') # pragma: no cover + pae = None + while i < fetch_till: + op, arg = t_path[i], t_path[i + 1] +- arg = arg_val(cur, arg, scope) +- if op == '[': ++ arg = arg_val(target, arg, scope) ++ if op == '.': + try: + cur = getattr(cur, arg) + except AttributeError as e: + pae = PathAccessError(e, Path(_t), i // 2) +- elif op == '.': ++ elif op == '[': + try: + cur = cur[arg] + except (KeyError, IndexError, TypeError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op == 'P': ++ # Path type stuff (fuzzy match) + get = scope[TargetRegistry].get_handler('get', cur, path=t_path[2:i+2:2]) + try: +- cur = get(scope, arg) ++ cur = get(cur, arg) + except Exception as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op in 'xX': + nxt = [] + get_handler = scope[TargetRegistry].get_handler +- if op == 'X': ++ if op == 'x': # increases arity of cur each time through ++ # TODO: so many try/except -- could scope[TargetRegistry] stuff be cached on type? + _extend_children(nxt, cur, get_handler) +- elif op == 'x': ++ elif op == 'X': + sofar = set() + _extend_children(nxt, cur, get_handler) + for item in nxt: + if id(item) not in sofar: ++ sofar.add(id(item)) + _extend_children(nxt, item, get_handler) +- sofar.add(id(item)) ++ nxt.insert(0, cur) ++ # handle the rest of the t_path in recursive calls + cur = [] + todo = TType() + todo.__ops__ = (root,) + t_path[i+2:] + for child in nxt: + try: +- cur.append(_t_eval(todo, child, scope)) ++ cur.append(_t_eval(child, todo, scope)) + except PathAccessError: + pass +- continue ++ break # we handled the rest in recursive call, break loop + elif op == '(': + args, kwargs = arg + scope[Path] += t_path[2:i+2:2] + cur = scope[glom]( +- target, Call(cur, kwargs, args), scope) +- else: ++ target, Call(cur, args, kwargs), scope) ++ # call with target rather than cur, ++ # because it is probably more intuitive ++ # if args to the call "reset" their path ++ # e.g. "T.a" should mean the same thing ++ # in both of these specs: T.a and T.b(T.a) ++ else: # arithmetic operators + try: +- if op == '-': ++ if op == '+': + cur = cur + arg +- elif op == '+': ++ elif op == '-': ++ cur = cur - arg ++ elif op == '*': + cur = cur * arg +- elif op == '//': +- cur = cur - arg ++ #elif op == '#': ++ # cur = cur // arg # TODO: python 2 friendly approach? + elif op == '/': + cur = cur / arg + elif op == '%': +- cur = cur // arg ++ cur = cur % arg + elif op == ':': + cur = cur ** arg + elif op == '&': ++ cur = cur & arg ++ elif op == '|': ++ cur = cur | arg ++ elif op == '^': + cur = cur ^ arg +- elif op == '|': +- cur = cur & arg +- elif op == '^': +- cur = cur | arg + elif op == '~': + cur = ~cur + elif op == '_': + cur = -cur +- except (ZeroDivisionError, TypeError) as e: ++ except (TypeError, ZeroDivisionError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + if pae: +- return scope +- i += 1 +- if root is not A: ++ raise pae ++ i += 2 ++ if root is A: + op, arg = t_path[-2:] +- if cur is target: +- op = '[' +- _assign_op(dest=cur, op=op, arg=arg, val=scope, path=_t, scope=target) +- return scope ++ if cur is scope: ++ op = '[' # all assignment on scope is setitem ++ _assign_op(dest=cur, op=op, arg=arg, val=target, path=_t, scope=scope) ++ return target # A should not change the target + return cur + + +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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1ea9bf095f91fe3329dd5c8c31c0eb9a6a9a7972 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:be68001023a802a4c3fe46cc08c44212a8b2cec5ac956ae851a414b1f4d2b41e" +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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..fc8696f15e47ce1f29f2ec5ecc55b3ad0bfc51e5 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_tutorial.py::test_tutorial" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_fallback", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..c8ba8e7e57e830c5b68452cd4fb233a7264cbbcf --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/canaries/first-hunk-only.sh @@ -0,0 +1,39 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/glom/core.py b/glom/core.py +index 6728907d4c636efeb028f33f269053088f108736..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -148,17 +148,22 @@ + self.__wrapped = exc + + def _finalize(self, scope): ++ # careful when changing how this functionality works; pytest seems to mess with ++ # the traceback module or sys.exc_info(). we saw different stacks when originally ++ # developing this in June 2020. + etype, evalue, _ = sys.exc_info() + tb_lines = traceback.format_exc().strip().splitlines() + limit = 0 +- for line in tb_lines: # Reversed logic in for loop ++ for line in reversed(tb_lines): + if _PKG_DIR_PATH in line: +- limit += 1 # Changed decrement to increment ++ limit -= 1 + break +- limit -= 1 # Changed increment to decrement +- self._tb_lines = tb_lines[:-limit] # Changed slicing to remove wrong lines +- if set(self._tb_lines[-1]) <= {' ', '^', '~'}: # Used last line instead of the first +- self._tb_lines = self._tb_lines[:-1] # Remove the last line ++ limit += 1 ++ self._tb_lines = tb_lines[-limit:] ++ # if the first line is trying to put a caret at a byte-code location on a line that ++ # isn't being displayed, skip it ++ if set(self._tb_lines[0]) <= {' ', '^', '~'}: ++ self._tb_lines = self._tb_lines[1:] + self._scope = scope + + def __str__(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/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__myb75dj6/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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..94b64db666a1010492e9b2522bf5894ef6a002ea --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "08a23261641203a41221ab7a3cdf507b36b106d472b2e22f9d06e4174e7216f8", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "3abac51872e05cc5df1a3932255cbaf22d0ca4933752545d76a193f068e01ca0", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "11a0fda751536b39a859d6621cf52f77250cf80455de9d2b65429efac7781d85", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "00781f8275a54e9e8a0b7c7929e79a7022c8262c", + "source_completion_sha256": "b23758473ecc0ab816e434aa95561c0b3d9049265737534f569191c364f43ba2", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "21528c0a2c42fc6f854b2ea0d721e506a5eb7e32714cdc64e486b628863a9544", + "is_fork": true, + "learner_path": "tasks/295d4415cf2c004888112338/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/00781f8275a54e9e8a0b7c7929e79a7022c8262c/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "413bdd4b3e899fb76930d2ef276c02abd953c8e5d304e523248909254299aa5b", + "provenance_path": "tasks/295d4415cf2c004888112338/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "00781f8275a54e9e8a0b7c7929e79a7022c8262c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d1c9d2874677a8bfa56f2a57149c517a69ce21ce", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "task_sha256": "62380c2cca69c8ed3ab79226d19d95e0759600beb7eed9f7964f2130318c6a7d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f556f4da674046062a304008fe4a80248539a4e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/instruction.md @@ -0,0 +1,58 @@ +# Incorrect string representation for Fold and Flatten classes + +## Description + +I've found an issue with the string representation of the `Fold` and `Flatten` classes in the `reduction.py` module. When trying to use these classes, their string representations are incorrect, which makes debugging difficult. + +## How to reproduce + +Here's a simple example that demonstrates the issue with `Fold`: + +```python +from glom import glom, Fold, T +import operator + +target = range(1, 5) +fold_obj = Fold(T, int) +print(repr(fold_obj)) # This produces incorrect output +``` + +Expected output: +``` +Fold(T, init=int) +``` + +Actual output: +``` +Fold(, init=int) +``` + +Similarly, for `Flatten`: + +```python +from glom import glom, Flatten, T + +target = [[1], [2], [3, 4]] +flatten_obj = Flatten() +print(repr(flatten_obj)) # This produces incorrect output +``` + +Expected output: +``` +Flatten() +``` + +Actual output: +``` +()(Flatten, init=list) +``` + +## Additional details + +The issue appears to be in the `__repr__` methods of both classes. For `Fold`, it seems to be incorrectly using `self.op` instead of `self.subspec` in the format_invocation call, and for `Flatten`, the arguments to format_invocation appear to be in the wrong order. + +This makes it difficult to debug code that uses these classes, as the string representations don't accurately reflect the objects' configurations. + +## 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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..55a40f78d65c38dc7c21a4771cf2cd146b31e201 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_flatten" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "d1c9d2874677a8bfa56f2a57149c517a69ce21ce", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "00781f8275a54e9e8a0b7c7929e79a7022c8262c" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_reduction.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": [ + "glom/reduction.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1424088, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "21528c0a2c42fc6f854b2ea0d721e506a5eb7e32714cdc64e486b628863a9544", + "is_fork": true, + "learner_path": "tasks/295d4415cf2c004888112338/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/00781f8275a54e9e8a0b7c7929e79a7022c8262c/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "413bdd4b3e899fb76930d2ef276c02abd953c8e5d304e523248909254299aa5b", + "provenance_path": "tasks/295d4415cf2c004888112338/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "00781f8275a54e9e8a0b7c7929e79a7022c8262c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d1c9d2874677a8bfa56f2a57149c517a69ce21ce", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "task_sha256": "62380c2cca69c8ed3ab79226d19d95e0759600beb7eed9f7964f2130318c6a7d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a481d0e57b1287abadd14135c16a1b18e6250262 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "08a23261641203a41221ab7a3cdf507b36b106d472b2e22f9d06e4174e7216f8", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/00781f8275a54e9e8a0b7c7929e79a7022c8262c/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b23758473ecc0ab816e434aa95561c0b3d9049265737534f569191c364f43ba2", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "faa11bf39743d28534aea5056f76e2394e8fe30c0a2d3ebc187fa017198981e8", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "21528c0a2c42fc6f854b2ea0d721e506a5eb7e32714cdc64e486b628863a9544", + "is_fork": true, + "learner_path": "tasks/295d4415cf2c004888112338/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/00781f8275a54e9e8a0b7c7929e79a7022c8262c/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "413bdd4b3e899fb76930d2ef276c02abd953c8e5d304e523248909254299aa5b", + "provenance_path": "tasks/295d4415cf2c004888112338/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "00781f8275a54e9e8a0b7c7929e79a7022c8262c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d1c9d2874677a8bfa56f2a57149c517a69ce21ce", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__n2puelt8", + "task_sha256": "62380c2cca69c8ed3ab79226d19d95e0759600beb7eed9f7964f2130318c6a7d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..aad202ac25c0a2054ee3eda6891ec3b0f1b05e33 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/provided-gold.diff @@ -0,0 +1,35 @@ +diff --git a/glom/reduction.py b/glom/reduction.py +index 7d6124d45f33d62d9daf5a2207c89094ef37b0fa..b400ce0d46e331e1d52f3924eb14ae1c38ef2ced 100644 +--- a/glom/reduction.py ++++ b/glom/reduction.py +@@ -99,9 +99,9 @@ + def __repr__(self): + cn = self.__class__.__name__ + kwargs = {'init': self.init} +- if self.op is not operator.isub: +- kwargs['op'] = self.init # Incorrect assignment of op to init +- return format_invocation(cn, (self.op,), kwargs, repr=bbrepr) # Changed self.subspec to self.op ++ if self.op is not operator.iadd: ++ kwargs['op'] = self.op ++ return format_invocation(cn, (self.subspec,), kwargs, repr=bbrepr) + + + class Sum(Fold): +@@ -177,13 +177,13 @@ + + def __repr__(self): + cn = self.__class__.__name__ +- args = (self.subspec,) if self.subspec is not T else () ++ args = () if self.subspec is T else (self.subspec,) + kwargs = {} +- if not self.lazy: ++ if self.lazy: + kwargs['init'] = 'lazy' +- elif self.init is list: ++ elif self.init is not list: + kwargs['init'] = self.init +- return format_invocation(args, cn, kwargs, repr=bbrepr) ++ return format_invocation(cn, args, kwargs, repr=bbrepr) + + + def flatten(target, **kwargs): diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..318e8d4f0c01b816b649f4d2435e0e8afa1093d0 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/solution/solve.sh @@ -0,0 +1,41 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/reduction.py b/glom/reduction.py +index 7d6124d45f33d62d9daf5a2207c89094ef37b0fa..b400ce0d46e331e1d52f3924eb14ae1c38ef2ced 100644 +--- a/glom/reduction.py ++++ b/glom/reduction.py +@@ -99,9 +99,9 @@ + def __repr__(self): + cn = self.__class__.__name__ + kwargs = {'init': self.init} +- if self.op is not operator.isub: +- kwargs['op'] = self.init # Incorrect assignment of op to init +- return format_invocation(cn, (self.op,), kwargs, repr=bbrepr) # Changed self.subspec to self.op ++ if self.op is not operator.iadd: ++ kwargs['op'] = self.op ++ return format_invocation(cn, (self.subspec,), kwargs, repr=bbrepr) + + + class Sum(Fold): +@@ -177,13 +177,13 @@ + + def __repr__(self): + cn = self.__class__.__name__ +- args = (self.subspec,) if self.subspec is not T else () ++ args = () if self.subspec is T else (self.subspec,) + kwargs = {} +- if not self.lazy: ++ if self.lazy: + kwargs['init'] = 'lazy' +- elif self.init is list: ++ elif self.init is not list: + kwargs['init'] = self.init +- return format_invocation(args, cn, kwargs, repr=bbrepr) ++ return format_invocation(cn, args, kwargs, repr=bbrepr) + + + def flatten(target, **kwargs): +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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9831cd91a7e68de9bdc8e0bf8c8084a1e63624a5 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:e5b2c71fce09d7e6761c34410eaf4b767feb9d2e0c0354200da6a16f07ccda7f" +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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..33e209d8b1c12b4c4e896c6e4b6b959daffd84d2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_flatten" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..4cbd5af1a172131c868643da676960ddf9af0bd2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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/glom/reduction.py b/glom/reduction.py +index 7d6124d45f33d62d9daf5a2207c89094ef37b0fa..b400ce0d46e331e1d52f3924eb14ae1c38ef2ced 100644 +--- a/glom/reduction.py ++++ b/glom/reduction.py +@@ -99,9 +99,9 @@ + def __repr__(self): + cn = self.__class__.__name__ + kwargs = {'init': self.init} +- if self.op is not operator.isub: +- kwargs['op'] = self.init # Incorrect assignment of op to init +- return format_invocation(cn, (self.op,), kwargs, repr=bbrepr) # Changed self.subspec to self.op ++ if self.op is not operator.iadd: ++ kwargs['op'] = self.op ++ return format_invocation(cn, (self.subspec,), kwargs, repr=bbrepr) + + + class Sum(Fold): +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/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__n2puelt8/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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..40a7fa1527ef80c34995ed29796e542700a9c31f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "bc9e84fef9f46d79989060db855d01f732152870106df34deb56c8c4e5dad8f7", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "b71432963c0044a39f409c12bcb204ed828627f6cff66bfae8aad7c56e3c8984", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "a9423c23cf94447c45eca4ca06df19d906d09c5be41e4accd482884dba4f0650", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "f3fd4b7beb81bd6f39113c20474ed001a5d093c4", + "source_completion_sha256": "1cc4d094c2566e90f31721a9195cb2b779d367bdc9f144eeb77b1d46a8042d67", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "327e6e383a9b8c39e4924cac9836bb2e50dc45ec8dcbef7b2be626ad3dca747d", + "is_fork": true, + "learner_path": "tasks/1c4923cf60ec54695cc86334/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f3fd4b7beb81bd6f39113c20474ed001a5d093c4/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "15a10c2429f82eae165c4c8f2315908db2d110ddad98e1d618dab59c998320cd", + "provenance_path": "tasks/1c4923cf60ec54695cc86334/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f3fd4b7beb81bd6f39113c20474ed001a5d093c4", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "179f04a4641d89eba1256e10ceedf4954850e7e4", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "task_sha256": "4eb873d3ef3761737cabca7e25a86f71c7d9160900c85fe1c22cd0116cf3dc6d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f85f69c2e9bf47683e19494110cfd05592d7332e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/instruction.md @@ -0,0 +1,38 @@ +Dict matching broken with Optional keys + +When using `Match` with dictionary specs containing `Optional` keys, the matching logic is completely broken. The precedence calculation and key handling has been corrupted, causing various failures. + +#### Steps/Code to Reproduce + +```python +from glom import glom, Match, Optional +import datetime + +# Basic Optional key matching fails +data = {'name': 'item', 'desc': 'a data item'} +spec = Match({'name': str, Optional('date_added'): datetime.datetime, 'desc': str}) + +try: + result = glom(data, spec) + print("Expected success, got:", result) +except Exception as e: + print("Unexpected error:", e) + +# Even simpler case fails +simple_data = {'a': 1} +simple_spec = Match({Optional('b', 'default'): str, 'a': int}) + +try: + result = glom(simple_data, simple_spec) + print("Expected success with default, got:", result) +except Exception as e: + print("Error with simple optional:", e) +``` + +The matching completely fails to work with Optional keys. Dictionary specs that should match successfully are throwing errors, and the precedence ordering for key matching appears to be completely wrong. + +This affects any use of `Match` with dictionary specifications containing `Optional` keys, which is a pretty common pattern for validating data structures with optional fields. + +## 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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..89f83aa69d9829dfec7e8ea55d040524c03dc45f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_nested_dict" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "179f04a4641d89eba1256e10ceedf4954850e7e4", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "f3fd4b7beb81bd6f39113c20474ed001a5d093c4" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_basic.py", + "glom/test/test_error.py", + "glom/test/test_match.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": [ + "glom/matching.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1380158, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "327e6e383a9b8c39e4924cac9836bb2e50dc45ec8dcbef7b2be626ad3dca747d", + "is_fork": true, + "learner_path": "tasks/1c4923cf60ec54695cc86334/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f3fd4b7beb81bd6f39113c20474ed001a5d093c4/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "15a10c2429f82eae165c4c8f2315908db2d110ddad98e1d618dab59c998320cd", + "provenance_path": "tasks/1c4923cf60ec54695cc86334/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f3fd4b7beb81bd6f39113c20474ed001a5d093c4", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "179f04a4641d89eba1256e10ceedf4954850e7e4", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "task_sha256": "4eb873d3ef3761737cabca7e25a86f71c7d9160900c85fe1c22cd0116cf3dc6d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a8d21da3453ebea15d5f82d496754627049486d9 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "bc9e84fef9f46d79989060db855d01f732152870106df34deb56c8c4e5dad8f7", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f3fd4b7beb81bd6f39113c20474ed001a5d093c4/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "1cc4d094c2566e90f31721a9195cb2b779d367bdc9f144eeb77b1d46a8042d67", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "904913fc56d7787963d0a4256fa774b7653df496c524ca870537bb74b97018a8", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "327e6e383a9b8c39e4924cac9836bb2e50dc45ec8dcbef7b2be626ad3dca747d", + "is_fork": true, + "learner_path": "tasks/1c4923cf60ec54695cc86334/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f3fd4b7beb81bd6f39113c20474ed001a5d093c4/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "15a10c2429f82eae165c4c8f2315908db2d110ddad98e1d618dab59c998320cd", + "provenance_path": "tasks/1c4923cf60ec54695cc86334/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f3fd4b7beb81bd6f39113c20474ed001a5d093c4", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "179f04a4641d89eba1256e10ceedf4954850e7e4", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__o69bwid6", + "task_sha256": "4eb873d3ef3761737cabca7e25a86f71c7d9160900c85fe1c22cd0116cf3dc6d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..f15a28e0cc4458000838db8c043f57c1f96037a9 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/provided-gold.diff @@ -0,0 +1,88 @@ +diff --git a/glom/matching.py b/glom/matching.py +index 2654d976c47713fafc3e86ffc23f0632460f3d95..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -295,6 +295,15 @@ + if type(self.children[0]) in (And, Or, Not): + return self.children[0]._m_repr() + return False ++ ++ def __repr__(self): ++ child_reprs = [_bool_child_repr(c) for c in self.children] ++ if self._m_repr() and self.default is _MISSING: ++ return f" {self.OP} ".join(child_reprs) ++ if self.default is not _MISSING: ++ child_reprs.append("default=" + repr(self.default)) ++ return self.__class__.__name__ + "(" + ", ".join(child_reprs) + ")" ++ + + class And(_Bool): + """ +@@ -652,50 +661,51 @@ + therefore we need a precedence for which order to try + keys in; higher = later + """ +- if type(match) in (Optional, Required): # Swapped Required and Optional ++ if type(match) in (Required, Optional): + match = match.key +- if type(match) in (frozenset, tuple): # Swapped tuple and frozenset ++ if type(match) in (tuple, frozenset): + if not match: +- return 1 # Changed from 0 to 1 for empty match +- return min([_precedence(item) for item in match]) # Changed max to min ++ return 0 ++ return max([_precedence(item) for item in match]) + if isinstance(match, type): +- return 3 # Changed from 2 to 3 ++ return 2 + if hasattr(match, "glomit"): +- return 2 # Changed from 1 to 2 +- return -1 # Changed from 0 to -1 ++ return 1 ++ return 0 # == match + + + def _handle_dict(target, spec, scope): + if not isinstance(target, dict): + raise TypeMatchError(type(target), dict) +- spec_keys = spec ++ spec_keys = spec # cheating a little bit here, list-vs-dict, but saves an object copy sometimes + + required = { + key for key in spec_keys +- if _precedence(key) == 1 and type(key) is not Optional ++ if _precedence(key) == 0 and type(key) is not Optional + or type(key) is Required} +- defaults = { ++ defaults = { # pre-load result with defaults + key.key: key.default for key in spec_keys +- if type(key) is Optional or key.default is _MISSING} ++ if type(key) is Optional and key.default is not _MISSING} + result = {} + for key, val in target.items(): + for maybe_spec_key in spec_keys: +- if type(maybe_spec_key) is Optional: ++ # handle Required as a special case here rather than letting it be a stand-alone spec ++ if type(maybe_spec_key) is Required: + spec_key = maybe_spec_key.key + else: + spec_key = maybe_spec_key + try: + key = scope[glom](key, spec_key, scope) + except GlomError: +- continue ++ pass + else: +- result[val] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) ++ result[key] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) + required.discard(maybe_spec_key) + break + else: +- pass ++ raise MatchError("key {0!r} didn't match any of {1!r}", key, spec_keys) + for key in set(defaults) - set(result): +- result[key] = defaults[key] ++ result[key] = arg_val(target, defaults[key], scope) + if required: + raise MatchError("target missing expected keys: {0}", ', '.join([bbrepr(r) for r in required])) + return result diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..32304a85f48849da70a21318dec2b42cc0b12ebc --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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/glom/matching.py b/glom/matching.py +index 2654d976c47713fafc3e86ffc23f0632460f3d95..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -295,6 +295,15 @@ + if type(self.children[0]) in (And, Or, Not): + return self.children[0]._m_repr() + return False ++ ++ def __repr__(self): ++ child_reprs = [_bool_child_repr(c) for c in self.children] ++ if self._m_repr() and self.default is _MISSING: ++ return f" {self.OP} ".join(child_reprs) ++ if self.default is not _MISSING: ++ child_reprs.append("default=" + repr(self.default)) ++ return self.__class__.__name__ + "(" + ", ".join(child_reprs) + ")" ++ + + class And(_Bool): + """ +@@ -652,50 +661,51 @@ + therefore we need a precedence for which order to try + keys in; higher = later + """ +- if type(match) in (Optional, Required): # Swapped Required and Optional ++ if type(match) in (Required, Optional): + match = match.key +- if type(match) in (frozenset, tuple): # Swapped tuple and frozenset ++ if type(match) in (tuple, frozenset): + if not match: +- return 1 # Changed from 0 to 1 for empty match +- return min([_precedence(item) for item in match]) # Changed max to min ++ return 0 ++ return max([_precedence(item) for item in match]) + if isinstance(match, type): +- return 3 # Changed from 2 to 3 ++ return 2 + if hasattr(match, "glomit"): +- return 2 # Changed from 1 to 2 +- return -1 # Changed from 0 to -1 ++ return 1 ++ return 0 # == match + + + def _handle_dict(target, spec, scope): + if not isinstance(target, dict): + raise TypeMatchError(type(target), dict) +- spec_keys = spec ++ spec_keys = spec # cheating a little bit here, list-vs-dict, but saves an object copy sometimes + + required = { + key for key in spec_keys +- if _precedence(key) == 1 and type(key) is not Optional ++ if _precedence(key) == 0 and type(key) is not Optional + or type(key) is Required} +- defaults = { ++ defaults = { # pre-load result with defaults + key.key: key.default for key in spec_keys +- if type(key) is Optional or key.default is _MISSING} ++ if type(key) is Optional and key.default is not _MISSING} + result = {} + for key, val in target.items(): + for maybe_spec_key in spec_keys: +- if type(maybe_spec_key) is Optional: ++ # handle Required as a special case here rather than letting it be a stand-alone spec ++ if type(maybe_spec_key) is Required: + spec_key = maybe_spec_key.key + else: + spec_key = maybe_spec_key + try: + key = scope[glom](key, spec_key, scope) + except GlomError: +- continue ++ pass + else: +- result[val] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) ++ result[key] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) + required.discard(maybe_spec_key) + break + else: +- pass ++ raise MatchError("key {0!r} didn't match any of {1!r}", key, spec_keys) + for key in set(defaults) - set(result): +- result[key] = defaults[key] ++ result[key] = arg_val(target, defaults[key], scope) + if required: + raise MatchError("target missing expected keys: {0}", ', '.join([bbrepr(r) for r in required])) + return result +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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..584695f23e431c862f11e72c57a986253c13a2c3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:0a79ab98d5524aaa16151c4cdc6915057b0988fc769937a5380fa4fa62876f0d" +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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..9e14bf1f93835185781642b683ce6421d3ae3fa4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_nested_dict" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..d304b92efd4c2335ae97cb47e22c40944a4c799f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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/glom/matching.py b/glom/matching.py +index 2654d976c47713fafc3e86ffc23f0632460f3d95..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -295,6 +295,15 @@ + if type(self.children[0]) in (And, Or, Not): + return self.children[0]._m_repr() + return False ++ ++ def __repr__(self): ++ child_reprs = [_bool_child_repr(c) for c in self.children] ++ if self._m_repr() and self.default is _MISSING: ++ return f" {self.OP} ".join(child_reprs) ++ if self.default is not _MISSING: ++ child_reprs.append("default=" + repr(self.default)) ++ return self.__class__.__name__ + "(" + ", ".join(child_reprs) + ")" ++ + + class And(_Bool): + """ +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/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__o69bwid6/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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..133ed086ae9b2a01ec21fb444a1c260908128f18 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "36995d6d255ad52fabe7ecc934ba2c21f0ffdbf78207e0775b0451073f604458", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "4399d121833923f6356a01dcb313a710a173edcaa3aba081d781a6ac02fa166b", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "d3292efebf08445aed4a96d583c201c08caea6a2626219f6673b5d4808bc814a", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "76d7bb39e26b122453ed0563a5cea99ac1dea0e7", + "source_completion_sha256": "2e247e9927c07e7d73c72066508fd86acf40fb595e95c93dd8c7439fd18c6fb0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "6d893e7596892acf617e66777cb0b9798abed03b56a752c544c5130dcd69265d", + "is_fork": true, + "learner_path": "tasks/81209c626054854d55a96c8f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/76d7bb39e26b122453ed0563a5cea99ac1dea0e7/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3b12298812527e84846a2eec8ee615dc09da919c195463f4a3c067c8bbc61627", + "provenance_path": "tasks/81209c626054854d55a96c8f/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "76d7bb39e26b122453ed0563a5cea99ac1dea0e7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a7405080b243dcde530a10a415afeb220ca27362", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "task_sha256": "94e1e9d5f78f95654aedcad13bbe443349f0b4fbfc5ea25b50e6c81c8493504b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6f95407ad75a633b64f9e0078093f0b1d26da19 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/instruction.md @@ -0,0 +1,35 @@ +Assign operation fails with "last part of path must be setattr or setitem" error + +When trying to use the `Assign` class to set values in nested data structures, I'm getting a `ValueError` saying "last part of path must be setattr or setitem". This seems to be happening even with simple assignment operations that should work. + +#### Steps/Code to Reproduce + +```python +from glom import glom, Assign, T + +# Simple assignment that should work +target = {} +result = glom(target, Assign(T['a'], 1)) +print(result) # Should print {'a': 1} +``` + +This raises: +``` +ValueError: last part of path must be setattr or setitem +``` + +The same error occurs with other assignment patterns: + +```python +from glom import assign + +# This also fails +target = {'alist': [0, 1, 2]} +assign(target, 'alist.2', 3) +``` + +It seems like the validation logic for checking if a path operation is valid for assignment is incorrectly rejecting valid setitem operations (like `T['key']` or list indexing). + +## 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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..94df8ad2558638c61f4993116f27894fdc3814fa --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_star_broadcast" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "a7405080b243dcde530a10a415afeb220ca27362", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "76d7bb39e26b122453ed0563a5cea99ac1dea0e7" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_mutation.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": [ + "glom/mutation.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1417864, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "6d893e7596892acf617e66777cb0b9798abed03b56a752c544c5130dcd69265d", + "is_fork": true, + "learner_path": "tasks/81209c626054854d55a96c8f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/76d7bb39e26b122453ed0563a5cea99ac1dea0e7/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3b12298812527e84846a2eec8ee615dc09da919c195463f4a3c067c8bbc61627", + "provenance_path": "tasks/81209c626054854d55a96c8f/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "76d7bb39e26b122453ed0563a5cea99ac1dea0e7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a7405080b243dcde530a10a415afeb220ca27362", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "task_sha256": "94e1e9d5f78f95654aedcad13bbe443349f0b4fbfc5ea25b50e6c81c8493504b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..7a494bbacb32a5bcecc4551a43649c8575e81b08 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "36995d6d255ad52fabe7ecc934ba2c21f0ffdbf78207e0775b0451073f604458", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/76d7bb39e26b122453ed0563a5cea99ac1dea0e7/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "2e247e9927c07e7d73c72066508fd86acf40fb595e95c93dd8c7439fd18c6fb0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "50e668963f03f8006b8e86bb163c44eaf972372ceb206119f0a5e44efaa25d2f", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "6d893e7596892acf617e66777cb0b9798abed03b56a752c544c5130dcd69265d", + "is_fork": true, + "learner_path": "tasks/81209c626054854d55a96c8f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/76d7bb39e26b122453ed0563a5cea99ac1dea0e7/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3b12298812527e84846a2eec8ee615dc09da919c195463f4a3c067c8bbc61627", + "provenance_path": "tasks/81209c626054854d55a96c8f/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "76d7bb39e26b122453ed0563a5cea99ac1dea0e7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a7405080b243dcde530a10a415afeb220ca27362", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__s3ov5uys", + "task_sha256": "94e1e9d5f78f95654aedcad13bbe443349f0b4fbfc5ea25b50e6c81c8493504b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..4c84e199e5c64a5f4c9d6d7c816f51f823ff8720 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/provided-gold.diff @@ -0,0 +1,49 @@ +diff --git a/glom/mutation.py b/glom/mutation.py +index 09610100f2f2075d0dd65a688d3d9c3bcbd830d5..c3fc322efb41f3f1a653d66eb364cd6690c7e6a5 100644 +--- a/glom/mutation.py ++++ b/glom/mutation.py +@@ -122,6 +122,9 @@ + + """ + def __init__(self, path, val, missing=None): ++ # TODO: an option like require_preexisting or something to ++ # ensure that a value is mutated, not just added. Current ++ # workaround is to do a Check(). + if isinstance(path, basestring): + path = Path.from_text(path) + elif type(path) is TType: +@@ -130,18 +133,19 @@ + raise TypeError('path argument must be a .-delimited string, Path, T, or S') + + try: +- self.op, self.arg = path.items()[0] ++ self.op, self.arg = path.items()[-1] + except IndexError: + raise ValueError('path must have at least one element') + self._orig_path = path + self.path = path[:-1] + +- if self.op not in '].P': ++ if self.op not in '[.P': ++ # maybe if we add null-coalescing this should do something? + raise ValueError('last part of path must be setattr or setitem') + self.val = val + + if missing is not None: +- if not callable(missing) or isinstance(missing, int): ++ if not callable(missing): + raise TypeError(f'expected missing to be callable, not {missing!r}') + self.missing = missing + +@@ -177,9 +181,9 @@ + + def __repr__(self): + cn = self.__class__.__name__ +- if self.missing is not None: ++ if self.missing is None: + return f'{cn}({self._orig_path!r}, {self.val!r})' +- return f'{cn}({self._orig_path!r}, {self.val!r}, missing={self.missing!r})' ++ return f'{cn}({self._orig_path!r}, {self.val!r}, missing={bbrepr(self.missing)})' + + + def assign(obj, path, val, missing=None): diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..522025f40e7ff33d3f4fb9c6662b5769f143bb62 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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/glom/mutation.py b/glom/mutation.py +index 09610100f2f2075d0dd65a688d3d9c3bcbd830d5..c3fc322efb41f3f1a653d66eb364cd6690c7e6a5 100644 +--- a/glom/mutation.py ++++ b/glom/mutation.py +@@ -122,6 +122,9 @@ + + """ + def __init__(self, path, val, missing=None): ++ # TODO: an option like require_preexisting or something to ++ # ensure that a value is mutated, not just added. Current ++ # workaround is to do a Check(). + if isinstance(path, basestring): + path = Path.from_text(path) + elif type(path) is TType: +@@ -130,18 +133,19 @@ + raise TypeError('path argument must be a .-delimited string, Path, T, or S') + + try: +- self.op, self.arg = path.items()[0] ++ self.op, self.arg = path.items()[-1] + except IndexError: + raise ValueError('path must have at least one element') + self._orig_path = path + self.path = path[:-1] + +- if self.op not in '].P': ++ if self.op not in '[.P': ++ # maybe if we add null-coalescing this should do something? + raise ValueError('last part of path must be setattr or setitem') + self.val = val + + if missing is not None: +- if not callable(missing) or isinstance(missing, int): ++ if not callable(missing): + raise TypeError(f'expected missing to be callable, not {missing!r}') + self.missing = missing + +@@ -177,9 +181,9 @@ + + def __repr__(self): + cn = self.__class__.__name__ +- if self.missing is not None: ++ if self.missing is None: + return f'{cn}({self._orig_path!r}, {self.val!r})' +- return f'{cn}({self._orig_path!r}, {self.val!r}, missing={self.missing!r})' ++ return f'{cn}({self._orig_path!r}, {self.val!r}, missing={bbrepr(self.missing)})' + + + def assign(obj, path, val, missing=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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f0d6762856985e4c206f5c94df06d3a553d5e1b8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:d551be31ce8029c7d4525d4d7d231829b6cfc88221e1b6b66397f3093001a518" +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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..70b23c5b946eeacddcc9548988efdbb2898b4282 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_star_broadcast" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..53d4608f3c51598e08233052fea07d4be414e3ea --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/canaries/first-hunk-only.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/glom/mutation.py b/glom/mutation.py +index 09610100f2f2075d0dd65a688d3d9c3bcbd830d5..c3fc322efb41f3f1a653d66eb364cd6690c7e6a5 100644 +--- a/glom/mutation.py ++++ b/glom/mutation.py +@@ -122,6 +122,9 @@ + + """ + def __init__(self, path, val, missing=None): ++ # TODO: an option like require_preexisting or something to ++ # ensure that a value is mutated, not just added. Current ++ # workaround is to do a Check(). + if isinstance(path, basestring): + path = Path.from_text(path) + elif type(path) is TType: +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/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__s3ov5uys/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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..0dad673cba1fd0629b5c560398f554cec0340efa --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "073f30e83aa8af454e9aa0ab282b3e5adc64b66d1791a86bcda1779afa5ada59", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "69a445b814e92a8347cd925da8238a4891c491ec56ebb5d3d55b57233f20d3c8", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "7e794535a7493b5d107a036e8acb376f1a6c56fd2e52b3e155b91830c6600283", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "6fafe918a58c8cf6e8987f22b35cd43bfae1b485", + "source_completion_sha256": "7ea19bc2fa92ee70bf9e59797e2b086652e7e29d5dddd9019683480bf02b58de", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "b2d9a5c2bcc1ba6703ead0be9c55770f71a59e0cfe95f2ad30b800e13c8a302f", + "is_fork": true, + "learner_path": "tasks/69cc7c2541fd3f344f0b5e99/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6fafe918a58c8cf6e8987f22b35cd43bfae1b485/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "8f95cd0eeedfb0464b76bf97b4ef846b495837b1c5b9f8985e046e3631158c3a", + "provenance_path": "tasks/69cc7c2541fd3f344f0b5e99/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6fafe918a58c8cf6e8987f22b35cd43bfae1b485", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6f566129496469c49c7d939dc45197c227153cdb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "task_sha256": "d1df1d525131ba5863fe91a4f8fe35b07f53492fd4ef4ada477de526b747c806", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2e471b26c20ffc31aa95de5aa44c62bc6cce7e58 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/instruction.md @@ -0,0 +1,45 @@ +# Matching functionality in glom is broken after recent changes + +## What happened? + +I was using the `Match` functionality in glom and noticed that several matching operations are now failing. It seems like the logic in the `_m_repr` method of the `Not` class and the `_precedence` function have been inverted, causing pattern matching to fail. + +## What did you expect to happen? + +I expected pattern matching to work correctly as it did before. Specifically, operations like `Match({'id': And(int, M == 1)})` should correctly match dictionaries with the specified pattern. + +## Minimal Complete Verifiable Example + +```python +import glom +from glom import glom, Match, M, T + +# This should work but now fails +target = [{'id': 0}, {'id': 1}, {'id': 2}] +result = glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) +# Expected: [{'id': 1}] +``` + +## Relevant log output + +When trying to use pattern matching with dictionaries, I get errors like: + +``` +glom.core.GlomError.wrap(AttributeError): error raised while processing match +``` + +And when using `Optional` keys: + +``` +ValueError: Optional() keys must have a default value +``` + +## Anything else we need to know? + +The issue seems to be in the `matching.py` file, particularly in the `Not._m_repr` method and the `_precedence` function. The logic appears to be inverted, causing pattern matching to fail. Also, there are issues with how `Required` and `Optional` keys are handled in dictionary matching. + +I've also noticed that the `_handle_dict` function has some issues with how it processes keys and values, which is causing nested dictionary matching to fail. + +## 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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..fce5c25a5fd338190e2d7f7550a0725ecfeaa802 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_nested_dict" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "6f566129496469c49c7d939dc45197c227153cdb", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "6fafe918a58c8cf6e8987f22b35cd43bfae1b485" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_match.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": [ + "glom/matching.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1412462, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "b2d9a5c2bcc1ba6703ead0be9c55770f71a59e0cfe95f2ad30b800e13c8a302f", + "is_fork": true, + "learner_path": "tasks/69cc7c2541fd3f344f0b5e99/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6fafe918a58c8cf6e8987f22b35cd43bfae1b485/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "8f95cd0eeedfb0464b76bf97b4ef846b495837b1c5b9f8985e046e3631158c3a", + "provenance_path": "tasks/69cc7c2541fd3f344f0b5e99/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6fafe918a58c8cf6e8987f22b35cd43bfae1b485", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6f566129496469c49c7d939dc45197c227153cdb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "task_sha256": "d1df1d525131ba5863fe91a4f8fe35b07f53492fd4ef4ada477de526b747c806", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..2998f2862e9eeda624b2b5b96713e18ae57cb4b0 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "073f30e83aa8af454e9aa0ab282b3e5adc64b66d1791a86bcda1779afa5ada59", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6fafe918a58c8cf6e8987f22b35cd43bfae1b485/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "7ea19bc2fa92ee70bf9e59797e2b086652e7e29d5dddd9019683480bf02b58de", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "846bc73641db51b57518cfc35370f4ec3888fbcab26247e4f7b425c9b1ebb45d", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "b2d9a5c2bcc1ba6703ead0be9c55770f71a59e0cfe95f2ad30b800e13c8a302f", + "is_fork": true, + "learner_path": "tasks/69cc7c2541fd3f344f0b5e99/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6fafe918a58c8cf6e8987f22b35cd43bfae1b485/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "8f95cd0eeedfb0464b76bf97b4ef846b495837b1c5b9f8985e046e3631158c3a", + "provenance_path": "tasks/69cc7c2541fd3f344f0b5e99/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6fafe918a58c8cf6e8987f22b35cd43bfae1b485", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6f566129496469c49c7d939dc45197c227153cdb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__tp6nxcix", + "task_sha256": "d1df1d525131ba5863fe91a4f8fe35b07f53492fd4ef4ada477de526b747c806", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..2a4920dc3aa467ed46809749e65e126d04f61c85 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/provided-gold.diff @@ -0,0 +1,87 @@ +diff --git a/glom/matching.py b/glom/matching.py +index 1f982b153573140cf7260a5092bf37e164295ca6..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -369,11 +369,11 @@ + raise GlomError("child shouldn't have passed", self.child) + + def _m_repr(self): +- if not isinstance(self.child, (_MType, _MExpr)): ++ if isinstance(self.child, (_MType, _MExpr)): + return True +- if type(self.child) in (And, Or, Not): ++ if type(self.child) not in (And, Or, Not): + return False +- return not self.child._m_repr() ++ return self.child._m_repr() + + def __repr__(self): + if self.child is M: +@@ -661,50 +661,51 @@ + therefore we need a precedence for which order to try + keys in; higher = later + """ +- if type(match) in (Optional, Required): # Swapped Required and Optional ++ if type(match) in (Required, Optional): + match = match.key +- if type(match) in (frozenset, tuple): # Swapped tuple and frozenset ++ if type(match) in (tuple, frozenset): + if not match: +- return 1 # Changed from 0 to 1 for empty match +- return min([_precedence(item) for item in match]) # Changed max to min ++ return 0 ++ return max([_precedence(item) for item in match]) + if isinstance(match, type): +- return 3 # Changed from 2 to 3 ++ return 2 + if hasattr(match, "glomit"): +- return 2 # Changed from 1 to 2 +- return -1 # Changed from 0 to -1 ++ return 1 ++ return 0 # == match + + + def _handle_dict(target, spec, scope): + if not isinstance(target, dict): + raise TypeMatchError(type(target), dict) +- spec_keys = spec ++ spec_keys = spec # cheating a little bit here, list-vs-dict, but saves an object copy sometimes + + required = { + key for key in spec_keys +- if _precedence(key) == 1 and type(key) is not Optional ++ if _precedence(key) == 0 and type(key) is not Optional + or type(key) is Required} +- defaults = { ++ defaults = { # pre-load result with defaults + key.key: key.default for key in spec_keys +- if type(key) is Optional or key.default is _MISSING} ++ if type(key) is Optional and key.default is not _MISSING} + result = {} + for key, val in target.items(): + for maybe_spec_key in spec_keys: +- if type(maybe_spec_key) is Optional: ++ # handle Required as a special case here rather than letting it be a stand-alone spec ++ if type(maybe_spec_key) is Required: + spec_key = maybe_spec_key.key + else: + spec_key = maybe_spec_key + try: + key = scope[glom](key, spec_key, scope) + except GlomError: +- continue ++ pass + else: +- result[val] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) ++ result[key] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) + required.discard(maybe_spec_key) + break + else: +- pass ++ raise MatchError("key {0!r} didn't match any of {1!r}", key, spec_keys) + for key in set(defaults) - set(result): +- result[key] = defaults[key] ++ result[key] = arg_val(target, defaults[key], scope) + if required: + raise MatchError("target missing expected keys: {0}", ', '.join([bbrepr(r) for r in required])) + return result diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..34c4d44407c66cd41685af16eec89f7d238bd258 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/solution/solve.sh @@ -0,0 +1,93 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/matching.py b/glom/matching.py +index 1f982b153573140cf7260a5092bf37e164295ca6..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -369,11 +369,11 @@ + raise GlomError("child shouldn't have passed", self.child) + + def _m_repr(self): +- if not isinstance(self.child, (_MType, _MExpr)): ++ if isinstance(self.child, (_MType, _MExpr)): + return True +- if type(self.child) in (And, Or, Not): ++ if type(self.child) not in (And, Or, Not): + return False +- return not self.child._m_repr() ++ return self.child._m_repr() + + def __repr__(self): + if self.child is M: +@@ -661,50 +661,51 @@ + therefore we need a precedence for which order to try + keys in; higher = later + """ +- if type(match) in (Optional, Required): # Swapped Required and Optional ++ if type(match) in (Required, Optional): + match = match.key +- if type(match) in (frozenset, tuple): # Swapped tuple and frozenset ++ if type(match) in (tuple, frozenset): + if not match: +- return 1 # Changed from 0 to 1 for empty match +- return min([_precedence(item) for item in match]) # Changed max to min ++ return 0 ++ return max([_precedence(item) for item in match]) + if isinstance(match, type): +- return 3 # Changed from 2 to 3 ++ return 2 + if hasattr(match, "glomit"): +- return 2 # Changed from 1 to 2 +- return -1 # Changed from 0 to -1 ++ return 1 ++ return 0 # == match + + + def _handle_dict(target, spec, scope): + if not isinstance(target, dict): + raise TypeMatchError(type(target), dict) +- spec_keys = spec ++ spec_keys = spec # cheating a little bit here, list-vs-dict, but saves an object copy sometimes + + required = { + key for key in spec_keys +- if _precedence(key) == 1 and type(key) is not Optional ++ if _precedence(key) == 0 and type(key) is not Optional + or type(key) is Required} +- defaults = { ++ defaults = { # pre-load result with defaults + key.key: key.default for key in spec_keys +- if type(key) is Optional or key.default is _MISSING} ++ if type(key) is Optional and key.default is not _MISSING} + result = {} + for key, val in target.items(): + for maybe_spec_key in spec_keys: +- if type(maybe_spec_key) is Optional: ++ # handle Required as a special case here rather than letting it be a stand-alone spec ++ if type(maybe_spec_key) is Required: + spec_key = maybe_spec_key.key + else: + spec_key = maybe_spec_key + try: + key = scope[glom](key, spec_key, scope) + except GlomError: +- continue ++ pass + else: +- result[val] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) ++ result[key] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) + required.discard(maybe_spec_key) + break + else: +- pass ++ raise MatchError("key {0!r} didn't match any of {1!r}", key, spec_keys) + for key in set(defaults) - set(result): +- result[key] = defaults[key] ++ result[key] = arg_val(target, defaults[key], scope) + if required: + raise MatchError("target missing expected keys: {0}", ', '.join([bbrepr(r) for r in required])) + return result +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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e1baec81e103197627617110fac0b7999687a4cc --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ee88875848991a97ba6237699f5d30d836e24730c3d0e176a6ba328f2443aee8" +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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..7f347038eea6ab19ae1160059be6c81521ce3483 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_nested_dict" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..2b5a71ec265a30827a610b009b2cc5fefbb67a3f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/canaries/first-hunk-only.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/glom/matching.py b/glom/matching.py +index 1f982b153573140cf7260a5092bf37e164295ca6..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -369,11 +369,11 @@ + raise GlomError("child shouldn't have passed", self.child) + + def _m_repr(self): +- if not isinstance(self.child, (_MType, _MExpr)): ++ if isinstance(self.child, (_MType, _MExpr)): + return True +- if type(self.child) in (And, Or, Not): ++ if type(self.child) not in (And, Or, Not): + return False +- return not self.child._m_repr() ++ return self.child._m_repr() + + def __repr__(self): + if self.child is M: +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/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__tp6nxcix/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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f4e76bc4da9cbd16e8374fdf02b9f3ed605f01b3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "f9f3ac4da16e75ce52da19aabc6e452e186a022df5c77021da1655512debc6c1", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "6cf0557a0fac1d3a5a9d2d62029fe3ffb50dfca98bb9220e31d60ea8486844f0", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "77e0f9dfee9d2609c4b292ddd770ec529bb89854ad8b44a5750ce2be867a0798", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "056cb96e558ce96a490988c80198dfe218cb0ea9", + "source_completion_sha256": "fdea8f18f6f2b0e2061c25dcec2042a6850326846214fe334bc7edfefaa588a4", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "fb9474d4183834eec98b924383bc176a8785e31f00686dd497679f02eac3edfd", + "is_fork": true, + "learner_path": "tasks/966bd3b81332de923724e317/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/056cb96e558ce96a490988c80198dfe218cb0ea9/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "27257a9872a7f3a55b09895a39226ba984986a40ac3d7b9506f00eb5cd5d06a0", + "provenance_path": "tasks/966bd3b81332de923724e317/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "056cb96e558ce96a490988c80198dfe218cb0ea9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "8a40ba9d6c3d072ebd8bf2d132184a1b873298c2", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "task_sha256": "eb44f943c62baf291cbdfdbc77f0396332ba2cba1bf1ea468d91ecbe398b0f56", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f6880a1b0999b09e0991e4cd9a0c5303197832d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/instruction.md @@ -0,0 +1,39 @@ +# Iter().filter() and Iter().windowed() methods not working as expected + +## Description + +The `Iter().filter()` and `Iter().windowed()` methods in the streaming module are not working correctly. + +### Filter issue + +When using `Iter().filter()` with a predicate function, it's filtering out the wrong items. For example: + +```python +from glom import glom, Iter + +is_odd = lambda x: x % 2 +odd_spec = Iter().filter(is_odd) +out = glom(range(5), odd_spec) +list(out) # Returns [] instead of [1, 3] +``` + +### Windowed issue + +The `Iter().windowed()` method is not returning the expected sliding window tuples: + +```python +from glom import glom, Iter + +int_list = list(range(5)) +spec = Iter().windowed(3) +out = glom(int_list, spec) +list(out) # Not returning [(0, 1, 2), (1, 2, 3), (2, 3, 4)] as expected +``` + +Additionally, it seems the windowed method is converting the result to a list when it should be returning an iterator. + +Both of these issues break existing code that relies on these methods working correctly. + +## 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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..88d6b37cd94f2a3689535e65355a51dbf25dd04d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_windowed" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "8a40ba9d6c3d072ebd8bf2d132184a1b873298c2", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "056cb96e558ce96a490988c80198dfe218cb0ea9" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_streaming.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": [ + "glom/streaming.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1422045, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "fb9474d4183834eec98b924383bc176a8785e31f00686dd497679f02eac3edfd", + "is_fork": true, + "learner_path": "tasks/966bd3b81332de923724e317/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/056cb96e558ce96a490988c80198dfe218cb0ea9/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "27257a9872a7f3a55b09895a39226ba984986a40ac3d7b9506f00eb5cd5d06a0", + "provenance_path": "tasks/966bd3b81332de923724e317/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "056cb96e558ce96a490988c80198dfe218cb0ea9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "8a40ba9d6c3d072ebd8bf2d132184a1b873298c2", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "task_sha256": "eb44f943c62baf291cbdfdbc77f0396332ba2cba1bf1ea468d91ecbe398b0f56", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..20f4e7f8b857966275b6deb183f2f11274db206d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "f9f3ac4da16e75ce52da19aabc6e452e186a022df5c77021da1655512debc6c1", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/056cb96e558ce96a490988c80198dfe218cb0ea9/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "fdea8f18f6f2b0e2061c25dcec2042a6850326846214fe334bc7edfefaa588a4", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f673a0e514e8e3918c950050d7bd2c125e42ffb5c71a77e7feb2d70e6b575296", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "fb9474d4183834eec98b924383bc176a8785e31f00686dd497679f02eac3edfd", + "is_fork": true, + "learner_path": "tasks/966bd3b81332de923724e317/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/056cb96e558ce96a490988c80198dfe218cb0ea9/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "27257a9872a7f3a55b09895a39226ba984986a40ac3d7b9506f00eb5cd5d06a0", + "provenance_path": "tasks/966bd3b81332de923724e317/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "056cb96e558ce96a490988c80198dfe218cb0ea9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "8a40ba9d6c3d072ebd8bf2d132184a1b873298c2", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__twn2ra0i", + "task_sha256": "eb44f943c62baf291cbdfdbc77f0396332ba2cba1bf1ea468d91ecbe398b0f56", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..ad1ec565c501ec066b9eb715f29f4aeac5b2c442 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/provided-gold.diff @@ -0,0 +1,31 @@ +diff --git a/glom/streaming.py b/glom/streaming.py +index 4153ed7cf90e7170362bea7dbaeebf2f0862d102..4da5fb50b26ace62b086106f7d731ca1d68840f0 100644 +--- a/glom/streaming.py ++++ b/glom/streaming.py +@@ -154,12 +154,15 @@ + [2, 3, 8] + + """ +- check_spec = key if isinstance(key, Check) else Check(key, default=T) ++ # NB: Check's validate function defaults to bool, and ++ # *default* is returned on access errors as well validation ++ # errors, so the lambda passed to ifilter below works fine. ++ check_spec = key if isinstance(key, Check) else Check(key, default=SKIP) + return self._add_op( + 'filter', + (key,), + lambda iterable, scope: ifilter( +- lambda t: scope[glom](t, check_spec, scope) is SKIP, iterable)) ++ lambda t: scope[glom](t, check_spec, scope) is not SKIP, iterable)) + + def chunked(self, size, fill=_MISSING): + """Return a new :class:`Iter()` spec which groups elements in the iterable +@@ -193,7 +196,7 @@ + [(0, 1), (1, 2), (2, 3)] + """ + return self._add_op( +- 'windowed', (size - 1,), lambda it, scope: list(windowed_iter(it, size))) ++ 'windowed', (size,), lambda it, scope: windowed_iter(it, size)) + + def split(self, sep=None, maxsplit=None): + """Return a new :class:`Iter()` spec which will lazily split an iterable based diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9fc2fbeac7ecba7128b8fd3388edf44639102be4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/solution/solve.sh @@ -0,0 +1,37 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/streaming.py b/glom/streaming.py +index 4153ed7cf90e7170362bea7dbaeebf2f0862d102..4da5fb50b26ace62b086106f7d731ca1d68840f0 100644 +--- a/glom/streaming.py ++++ b/glom/streaming.py +@@ -154,12 +154,15 @@ + [2, 3, 8] + + """ +- check_spec = key if isinstance(key, Check) else Check(key, default=T) ++ # NB: Check's validate function defaults to bool, and ++ # *default* is returned on access errors as well validation ++ # errors, so the lambda passed to ifilter below works fine. ++ check_spec = key if isinstance(key, Check) else Check(key, default=SKIP) + return self._add_op( + 'filter', + (key,), + lambda iterable, scope: ifilter( +- lambda t: scope[glom](t, check_spec, scope) is SKIP, iterable)) ++ lambda t: scope[glom](t, check_spec, scope) is not SKIP, iterable)) + + def chunked(self, size, fill=_MISSING): + """Return a new :class:`Iter()` spec which groups elements in the iterable +@@ -193,7 +196,7 @@ + [(0, 1), (1, 2), (2, 3)] + """ + return self._add_op( +- 'windowed', (size - 1,), lambda it, scope: list(windowed_iter(it, size))) ++ 'windowed', (size,), lambda it, scope: windowed_iter(it, size)) + + def split(self, sep=None, maxsplit=None): + """Return a new :class:`Iter()` spec which will lazily split an iterable based +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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a874930d9c8d41d07873834cb55d29d1c57b5fd9 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:1dea2b06147cf69d1cad0bf52dc7f3fe84d157a530d16e93f84242baf733c076" +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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..86661936b733cf9580f6f58a27b9632ca4ee3651 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_windowed" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..97c63d3d3ad9370c511b12a710ebc76782203f93 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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/glom/streaming.py b/glom/streaming.py +index 4153ed7cf90e7170362bea7dbaeebf2f0862d102..4da5fb50b26ace62b086106f7d731ca1d68840f0 100644 +--- a/glom/streaming.py ++++ b/glom/streaming.py +@@ -154,12 +154,15 @@ + [2, 3, 8] + + """ +- check_spec = key if isinstance(key, Check) else Check(key, default=T) ++ # NB: Check's validate function defaults to bool, and ++ # *default* is returned on access errors as well validation ++ # errors, so the lambda passed to ifilter below works fine. ++ check_spec = key if isinstance(key, Check) else Check(key, default=SKIP) + return self._add_op( + 'filter', + (key,), + lambda iterable, scope: ifilter( +- lambda t: scope[glom](t, check_spec, scope) is SKIP, iterable)) ++ lambda t: scope[glom](t, check_spec, scope) is not SKIP, iterable)) + + def chunked(self, size, fill=_MISSING): + """Return a new :class:`Iter()` spec which groups elements in the iterable +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/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__twn2ra0i/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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f549085c7d2c113be59175ed2b48965f9da5de73 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "2cc13cfff7345bc64b3e4c3789466ffafb993ae32a793a017b5b47f68e76bdc8", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "49c3edefcdf0c44f12c1b14972759c75e80d05fdcb4a2be7a15a5f40805ab5db", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "676b99f2dadea8b42e25226c137acdb728666e565cbd69950582339e79bcdb0c", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "c8408045d07b3368bfb3db0e56afd68805620932", + "source_completion_sha256": "13af475c93ad65d1ea39cbaaede3c380a6b6cbec8cea2907220a175e813a6e4b", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "99aad53f823a90a05e87d5fc519c3232ee0e768966c929fd6e8306dff3a563cf", + "is_fork": true, + "learner_path": "tasks/fdf203bbc3b1c8434857f76e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/c8408045d07b3368bfb3db0e56afd68805620932/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "a97fa3d484752cfd0186becc957504d4e2c717cde2d890a630064695ce671b75", + "provenance_path": "tasks/fdf203bbc3b1c8434857f76e/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "c8408045d07b3368bfb3db0e56afd68805620932", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ada32830efc90e8388d946060ecfaa34148e04f2", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "task_sha256": "48eaff62f9b50439643622eba72c5ae9e1950c1808e1f2bb893276fdda2667a2", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e31a5fcaa4f61c6cb75ef13ec078540f53c2e9d7 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/instruction.md @@ -0,0 +1,61 @@ +# glom CLI command swaps target and spec parameters + +#### Description + +The glom CLI command is swapping the target and spec parameters, causing unexpected behavior when using the command line interface. + +#### Steps to Reproduce + +```python +from glom import glom +import subprocess + +# This works correctly in the Python API +result = glom({"a": {"b": "c"}}, "a.b") +print(result) # => "c" + +# But the CLI version swaps the arguments +# Expected: should output "c" +subprocess.check_output(['glom', 'a.b', '{"a": {"b": "c"}}']) +# Actual: Fails with error +``` + +When using the CLI directly: + +```bash +# This should work but fails +glom a.b '{"a": {"b": "c"}}' + +# This works but is backwards from the API +glom '{"a": {"b": "c"}}' a.b +``` + +#### Expected Results + +The CLI should maintain the same parameter order as the Python API: +- First parameter: target (the data to operate on) +- Second parameter: spec (how to transform the data) + +#### Actual Results + +The CLI is swapping the parameters: +- First parameter is being treated as the spec +- Second parameter is being treated as the target + +Additionally, there are several other issues with the CLI: +- Default formats are incorrect (yaml instead of json) +- The `--scalar` flag behavior is inverted +- Debug and inspect flags have swapped behavior +- Return codes are incorrect for errors + +#### Versions +``` +Python 3.10 +glom latest version +``` + + + +## 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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9365f8242608f9c42fb390d53fc88a7b2b62cae0 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "ada32830efc90e8388d946060ecfaa34148e04f2", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "c8408045d07b3368bfb3db0e56afd68805620932" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_cli.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": [ + "glom/cli.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1421786, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "99aad53f823a90a05e87d5fc519c3232ee0e768966c929fd6e8306dff3a563cf", + "is_fork": true, + "learner_path": "tasks/fdf203bbc3b1c8434857f76e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/c8408045d07b3368bfb3db0e56afd68805620932/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "a97fa3d484752cfd0186becc957504d4e2c717cde2d890a630064695ce671b75", + "provenance_path": "tasks/fdf203bbc3b1c8434857f76e/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "c8408045d07b3368bfb3db0e56afd68805620932", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ada32830efc90e8388d946060ecfaa34148e04f2", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "task_sha256": "48eaff62f9b50439643622eba72c5ae9e1950c1808e1f2bb893276fdda2667a2", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..9aebe4b7e7850ccf8e185d967ed2b7faa1b8bb47 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "2cc13cfff7345bc64b3e4c3789466ffafb993ae32a793a017b5b47f68e76bdc8", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/c8408045d07b3368bfb3db0e56afd68805620932/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "13af475c93ad65d1ea39cbaaede3c380a6b6cbec8cea2907220a175e813a6e4b", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "eb46dfae5255fe1bfe9f12141a978fcf499d6836cb114ee3851740541f764263", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "99aad53f823a90a05e87d5fc519c3232ee0e768966c929fd6e8306dff3a563cf", + "is_fork": true, + "learner_path": "tasks/fdf203bbc3b1c8434857f76e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/c8408045d07b3368bfb3db0e56afd68805620932/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "a97fa3d484752cfd0186becc957504d4e2c717cde2d890a630064695ce671b75", + "provenance_path": "tasks/fdf203bbc3b1c8434857f76e/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "c8408045d07b3368bfb3db0e56afd68805620932", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ada32830efc90e8388d946060ecfaa34148e04f2", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__vefrzb46", + "task_sha256": "48eaff62f9b50439643622eba72c5ae9e1950c1808e1f2bb893276fdda2667a2", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..fa6a0ba9880fe07e5ed7aa28594543c753a9fb46 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/provided-gold.diff @@ -0,0 +1,106 @@ +diff --git a/glom/cli.py b/glom/cli.py +index 70975298edf277d30633a9b7e2ef444bd5c6cfdd..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -53,44 +53,44 @@ + """Command-line interface to the glom library, providing nested data + access and data restructuring with the power of Python. + """ +- if debug or not inspect: ++ if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +- echo=debug, ++ echo=inspect, + recursive=inspect, +- breakpoint=debug and stdin_open, +- post_mortem=inspect and stdin_open) ++ breakpoint=inspect and stdin_open, ++ post_mortem=debug and stdin_open) + + try: +- result = glom.glom(spec, target) ++ result = glom.glom(target, spec) + except GlomError as ge: + print(f'{ge.__class__.__name__}: {ge}') +- return 0 ++ return 1 + + if not indent: +- indent = 0 ++ indent = None + +- if scalar or is_scalar(result): +- print(result, end=' ') ++ if scalar and is_scalar(result): ++ print(result, end='') + else: +- print(json.dumps(result, indent=indent, sort_keys=False)) ++ print(json.dumps(result, indent=indent, sort_keys=True)) + return + + + def get_command(): +- posargs = PosArgSpec(str, max_count=1, display={'label': '[spec [target]]'}) ++ posargs = PosArgSpec(str, max_count=2, display={'label': '[spec [target]]'}) + cmd = Command(glom_cli, posargs=posargs, middlewares=[mw_get_target]) + cmd.add('--target-file', str, missing=None, doc='path to target data source') +- cmd.add('--target-format', str, missing='yaml', ++ cmd.add('--target-format', str, missing='json', + doc='format of the source data (json or python)') + cmd.add('--spec-file', str, missing=None, doc='path to glom spec definition') +- cmd.add('--spec-format', str, missing='json', ++ cmd.add('--spec-format', str, missing='python', + doc='format of the glom spec definition (json, python, python-full)') + +- cmd.add('--indent', int, missing=0, ++ cmd.add('--indent', int, missing=2, + doc='number of spaces to indent the result, 0 to disable pretty-printing') + +- cmd.add('--scalar', parse_as=False, ++ cmd.add('--scalar', parse_as=True, + doc="if the result is a single value (not a collection), output it" + " without quotes or whitespace, for easier usage in scripts") + cmd.add('--debug', parse_as=True, doc='interactively debug any errors that come up') +@@ -100,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): +@@ -170,7 +170,7 @@ + if len(posargs_) == 2: + spec_text, target_text = posargs_ + elif len(posargs_) == 1: +- spec_text, target_text = posargs_[0], '' ++ spec_text, target_text = posargs_[0], None + + if spec_text and spec_file: + raise UsageError('expected spec file or spec argument, not both') +@@ -183,11 +183,12 @@ + + if not spec_text: + spec = Path() +- elif spec_format == 'json': ++ elif spec_format == 'python': + if spec_text[0] not in ('"', "'", "[", "{", "("): ++ # intention: handle trivial path access, assume string + spec_text = repr(spec_text) + spec = ast.literal_eval(spec_text) +- elif spec_format == 'python': ++ elif spec_format == 'json': + spec = json.loads(spec_text) + elif spec_format == 'python-full': + spec = _eval_python_full_spec(spec_text) +@@ -208,7 +209,7 @@ + + target = mw_handle_target(target_text, target_format) + +- return next_(spec=target, target=spec) ++ return next_(spec=spec, target=target) + + + def _from_glom_import_star(): diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..3a91aa803e8b3ad06e89037babb31ec3852a23b2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/solution/solve.sh @@ -0,0 +1,112 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/cli.py b/glom/cli.py +index 70975298edf277d30633a9b7e2ef444bd5c6cfdd..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -53,44 +53,44 @@ + """Command-line interface to the glom library, providing nested data + access and data restructuring with the power of Python. + """ +- if debug or not inspect: ++ if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +- echo=debug, ++ echo=inspect, + recursive=inspect, +- breakpoint=debug and stdin_open, +- post_mortem=inspect and stdin_open) ++ breakpoint=inspect and stdin_open, ++ post_mortem=debug and stdin_open) + + try: +- result = glom.glom(spec, target) ++ result = glom.glom(target, spec) + except GlomError as ge: + print(f'{ge.__class__.__name__}: {ge}') +- return 0 ++ return 1 + + if not indent: +- indent = 0 ++ indent = None + +- if scalar or is_scalar(result): +- print(result, end=' ') ++ if scalar and is_scalar(result): ++ print(result, end='') + else: +- print(json.dumps(result, indent=indent, sort_keys=False)) ++ print(json.dumps(result, indent=indent, sort_keys=True)) + return + + + def get_command(): +- posargs = PosArgSpec(str, max_count=1, display={'label': '[spec [target]]'}) ++ posargs = PosArgSpec(str, max_count=2, display={'label': '[spec [target]]'}) + cmd = Command(glom_cli, posargs=posargs, middlewares=[mw_get_target]) + cmd.add('--target-file', str, missing=None, doc='path to target data source') +- cmd.add('--target-format', str, missing='yaml', ++ cmd.add('--target-format', str, missing='json', + doc='format of the source data (json or python)') + cmd.add('--spec-file', str, missing=None, doc='path to glom spec definition') +- cmd.add('--spec-format', str, missing='json', ++ cmd.add('--spec-format', str, missing='python', + doc='format of the glom spec definition (json, python, python-full)') + +- cmd.add('--indent', int, missing=0, ++ cmd.add('--indent', int, missing=2, + doc='number of spaces to indent the result, 0 to disable pretty-printing') + +- cmd.add('--scalar', parse_as=False, ++ cmd.add('--scalar', parse_as=True, + doc="if the result is a single value (not a collection), output it" + " without quotes or whitespace, for easier usage in scripts") + cmd.add('--debug', parse_as=True, doc='interactively debug any errors that come up') +@@ -100,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): +@@ -170,7 +170,7 @@ + if len(posargs_) == 2: + spec_text, target_text = posargs_ + elif len(posargs_) == 1: +- spec_text, target_text = posargs_[0], '' ++ spec_text, target_text = posargs_[0], None + + if spec_text and spec_file: + raise UsageError('expected spec file or spec argument, not both') +@@ -183,11 +183,12 @@ + + if not spec_text: + spec = Path() +- elif spec_format == 'json': ++ elif spec_format == 'python': + if spec_text[0] not in ('"', "'", "[", "{", "("): ++ # intention: handle trivial path access, assume string + spec_text = repr(spec_text) + spec = ast.literal_eval(spec_text) +- elif spec_format == 'python': ++ elif spec_format == 'json': + spec = json.loads(spec_text) + elif spec_format == 'python-full': + spec = _eval_python_full_spec(spec_text) +@@ -208,7 +209,7 @@ + + target = mw_handle_target(target_text, target_format) + +- return next_(spec=target, target=spec) ++ return next_(spec=spec, target=target) + + + def _from_glom_import_star(): +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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..30d5612c59c1c8e992217661e90e525bf4bd0b43 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:6b3ef524144950fb9579a2a231d37277c80aca4609a00939c10f97a9ef60a902" +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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..1f19c39e9ee5ecbe918118424a1ad464f03bc12e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..53b0c141a63f0b57a4ee14eced1a27ff5443d031 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/canaries/first-hunk-only.sh @@ -0,0 +1,70 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/glom/cli.py b/glom/cli.py +index 70975298edf277d30633a9b7e2ef444bd5c6cfdd..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -53,44 +53,44 @@ + """Command-line interface to the glom library, providing nested data + access and data restructuring with the power of Python. + """ +- if debug or not inspect: ++ if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +- echo=debug, ++ echo=inspect, + recursive=inspect, +- breakpoint=debug and stdin_open, +- post_mortem=inspect and stdin_open) ++ breakpoint=inspect and stdin_open, ++ post_mortem=debug and stdin_open) + + try: +- result = glom.glom(spec, target) ++ result = glom.glom(target, spec) + except GlomError as ge: + print(f'{ge.__class__.__name__}: {ge}') +- return 0 ++ return 1 + + if not indent: +- indent = 0 ++ indent = None + +- if scalar or is_scalar(result): +- print(result, end=' ') ++ if scalar and is_scalar(result): ++ print(result, end='') + else: +- print(json.dumps(result, indent=indent, sort_keys=False)) ++ print(json.dumps(result, indent=indent, sort_keys=True)) + return + + + def get_command(): +- posargs = PosArgSpec(str, max_count=1, display={'label': '[spec [target]]'}) ++ posargs = PosArgSpec(str, max_count=2, display={'label': '[spec [target]]'}) + cmd = Command(glom_cli, posargs=posargs, middlewares=[mw_get_target]) + cmd.add('--target-file', str, missing=None, doc='path to target data source') +- cmd.add('--target-format', str, missing='yaml', ++ cmd.add('--target-format', str, missing='json', + doc='format of the source data (json or python)') + cmd.add('--spec-file', str, missing=None, doc='path to glom spec definition') +- cmd.add('--spec-format', str, missing='json', ++ cmd.add('--spec-format', str, missing='python', + doc='format of the glom spec definition (json, python, python-full)') + +- cmd.add('--indent', int, missing=0, ++ cmd.add('--indent', int, missing=2, + doc='number of spaces to indent the result, 0 to disable pretty-printing') + +- cmd.add('--scalar', parse_as=False, ++ cmd.add('--scalar', parse_as=True, + doc="if the result is a single value (not a collection), output it" + " without quotes or whitespace, for easier usage in scripts") + cmd.add('--debug', parse_as=True, doc='interactively debug any errors that come up') +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/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__vefrzb46/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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f94d2baffd49a08991ad83b3ef9cfeea971a4410 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "3972d8d27332106a1ad8c35a32198157254c29e553a45e60fa6e62f50c56125a", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "0b16732077afb07ec1a9f4a79d480a7c58b5581dc9873572943553eac42f370e", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "fcd0284068eea5e0564f798a24c4a65eacf10a95adb4029d2bc01cc718cb6b33", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "6b7599a9428152fcbc3aabf0e3b5b9a98e138d81", + "source_completion_sha256": "b8e3ac4f91ec7e53513730164b0ea997a2c767acaa31d1d3b3dc1f061f6a03d7", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "679736e45a1ab970b990754fbe5c4266f2aabc44d4c58045183b9ab1c42bbd77", + "is_fork": true, + "learner_path": "tasks/a02ccc150164e19d27808914/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6b7599a9428152fcbc3aabf0e3b5b9a98e138d81/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "e72b859ef6b53570cbf514c1634a6218b5804c69aa5684213821fdcd863e5fa2", + "provenance_path": "tasks/a02ccc150164e19d27808914/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6b7599a9428152fcbc3aabf0e3b5b9a98e138d81", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b661975f4b7aaaa185d28d83e421b1f1d1535b1b", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "task_sha256": "6eca3a0aa639a6a507400c6295fcd49fd0086073f087a12b42e77be31aa49ba6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbc37756f6f051c7651f857f174c8fc93f9a2461 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/instruction.md @@ -0,0 +1,34 @@ +CLI argument order swapped causing incorrect behavior + +#### Description + +The glom CLI is not working correctly - it appears the target and spec arguments have been swapped internally, causing glom operations to fail or produce unexpected results. + +#### Steps/Code to Reproduce + +```bash +# Basic usage that should work +echo '{"a": {"b": 1}}' | glom 'a.b' + +# This should return 1 but instead produces an error or unexpected output +``` + +Also reproducible with: + +```bash +glom '{"a": {"b": 1}}' 'a.b' +``` + +The CLI seems to be passing arguments in the wrong order to the core glom function, where it should be `glom(target, spec)` but appears to be calling `glom(spec, target)`. + +#### Expected Behavior + +The CLI should correctly extract nested values from JSON/data structures using the provided spec, just like the Python API does with `glom(target, spec)`. + +#### Actual Behavior + +The CLI produces errors or unexpected output because the target and spec arguments are being passed in the wrong order to the underlying glom function. + +## 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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5df0d62b43252101db9ca139cdf80dfe891e7489 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "b661975f4b7aaaa185d28d83e421b1f1d1535b1b", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "6b7599a9428152fcbc3aabf0e3b5b9a98e138d81" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_cli.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": [ + "glom/cli.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1421926, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "679736e45a1ab970b990754fbe5c4266f2aabc44d4c58045183b9ab1c42bbd77", + "is_fork": true, + "learner_path": "tasks/a02ccc150164e19d27808914/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6b7599a9428152fcbc3aabf0e3b5b9a98e138d81/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "e72b859ef6b53570cbf514c1634a6218b5804c69aa5684213821fdcd863e5fa2", + "provenance_path": "tasks/a02ccc150164e19d27808914/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6b7599a9428152fcbc3aabf0e3b5b9a98e138d81", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b661975f4b7aaaa185d28d83e421b1f1d1535b1b", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "task_sha256": "6eca3a0aa639a6a507400c6295fcd49fd0086073f087a12b42e77be31aa49ba6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..cd8adae0a78901b6fa9b2f24b9edb8c612c0305c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "3972d8d27332106a1ad8c35a32198157254c29e553a45e60fa6e62f50c56125a", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6b7599a9428152fcbc3aabf0e3b5b9a98e138d81/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b8e3ac4f91ec7e53513730164b0ea997a2c767acaa31d1d3b3dc1f061f6a03d7", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "6232dbf4b1d228116cdc101e20332a59c3e49ec6d63546c7e935a43455947063", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "679736e45a1ab970b990754fbe5c4266f2aabc44d4c58045183b9ab1c42bbd77", + "is_fork": true, + "learner_path": "tasks/a02ccc150164e19d27808914/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6b7599a9428152fcbc3aabf0e3b5b9a98e138d81/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "e72b859ef6b53570cbf514c1634a6218b5804c69aa5684213821fdcd863e5fa2", + "provenance_path": "tasks/a02ccc150164e19d27808914/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6b7599a9428152fcbc3aabf0e3b5b9a98e138d81", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b661975f4b7aaaa185d28d83e421b1f1d1535b1b", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__wlazrhs7", + "task_sha256": "6eca3a0aa639a6a507400c6295fcd49fd0086073f087a12b42e77be31aa49ba6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..960abbd953baa969a64d07d3770de6389323221c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/provided-gold.diff @@ -0,0 +1,51 @@ +diff --git a/glom/cli.py b/glom/cli.py +index d178e49509f32e4909a68482b4e9dff072a82034..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -53,27 +53,27 @@ + """Command-line interface to the glom library, providing nested data + access and data restructuring with the power of Python. + """ +- if debug or not inspect: ++ if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +- echo=debug, ++ echo=inspect, + recursive=inspect, +- breakpoint=debug and stdin_open, +- post_mortem=inspect and stdin_open) ++ breakpoint=inspect and stdin_open, ++ post_mortem=debug and stdin_open) + + try: +- result = glom.glom(spec, target) ++ result = glom.glom(target, spec) + except GlomError as ge: + print(f'{ge.__class__.__name__}: {ge}') +- return 0 ++ return 1 + + if not indent: +- indent = 0 ++ indent = None + +- if scalar or is_scalar(result): +- print(result, end=' ') ++ if scalar and is_scalar(result): ++ print(result, end='') + else: +- print(json.dumps(result, indent=indent, sort_keys=False)) ++ print(json.dumps(result, indent=indent, sort_keys=True)) + return + + +@@ -100,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..25e3e02d1bcdd1799cbeb94d99e535d670625cde --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/solution/solve.sh @@ -0,0 +1,57 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/cli.py b/glom/cli.py +index d178e49509f32e4909a68482b4e9dff072a82034..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -53,27 +53,27 @@ + """Command-line interface to the glom library, providing nested data + access and data restructuring with the power of Python. + """ +- if debug or not inspect: ++ if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +- echo=debug, ++ echo=inspect, + recursive=inspect, +- breakpoint=debug and stdin_open, +- post_mortem=inspect and stdin_open) ++ breakpoint=inspect and stdin_open, ++ post_mortem=debug and stdin_open) + + try: +- result = glom.glom(spec, target) ++ result = glom.glom(target, spec) + except GlomError as ge: + print(f'{ge.__class__.__name__}: {ge}') +- return 0 ++ return 1 + + if not indent: +- indent = 0 ++ indent = None + +- if scalar or is_scalar(result): +- print(result, end=' ') ++ if scalar and is_scalar(result): ++ print(result, end='') + else: +- print(json.dumps(result, indent=indent, sort_keys=False)) ++ print(json.dumps(result, indent=indent, sort_keys=True)) + return + + +@@ -100,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): +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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..738e0efc280ff57bfb761958a821b76a9ec35155 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:882e4a6182117eeed0d4f1ecd9adbb45f25bd7d8e6153900bc440a3760768e3e" +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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..044e0bc8b8b2212d4c6c99567c771a4cb10d9001 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ca9ee4aed141f849c110d702cac456412fd31e4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/canaries/first-hunk-only.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/glom/cli.py b/glom/cli.py +index d178e49509f32e4909a68482b4e9dff072a82034..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -53,27 +53,27 @@ + """Command-line interface to the glom library, providing nested data + access and data restructuring with the power of Python. + """ +- if debug or not inspect: ++ if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, +- echo=debug, ++ echo=inspect, + recursive=inspect, +- breakpoint=debug and stdin_open, +- post_mortem=inspect and stdin_open) ++ breakpoint=inspect and stdin_open, ++ post_mortem=debug and stdin_open) + + try: +- result = glom.glom(spec, target) ++ result = glom.glom(target, spec) + except GlomError as ge: + print(f'{ge.__class__.__name__}: {ge}') +- return 0 ++ return 1 + + if not indent: +- indent = 0 ++ indent = None + +- if scalar or is_scalar(result): +- print(result, end=' ') ++ if scalar and is_scalar(result): ++ print(result, end='') + else: +- print(json.dumps(result, indent=indent, sort_keys=False)) ++ print(json.dumps(result, indent=indent, sort_keys=True)) + return + + +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/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__wlazrhs7/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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/adapter.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..48b2ae7ce47f1172dfe28221247e2fa2f80d5a73 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "bb336f058f0332a12e3d35f5f0a2fe0d5dda9e428e41483c5141624783d2f63f", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "0f0c1ce86013a9d891f7231b6f4f3dee5c3e791a840146484028fe3df9b69598", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "b2ebd51cf0ac69736f89e6d2d13e018600b4b6312cc9f4eb1ba418d0ef00d72b", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "438db0c531d8faf5512af23eae04dc4c6854dcf0", + "source_completion_sha256": "54caab041f53c7a53c6a89725d74ef7f2eff9703a133c0691379fcf431a22a63", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "6ebf72bda451a4c87b7790874147b3f0f295fc51ca0b4cfda9a7f2690329d650", + "is_fork": true, + "learner_path": "tasks/16bda90956705b1aafcf7c24/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/438db0c531d8faf5512af23eae04dc4c6854dcf0/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "0c7ec10234a0ebbc0754cba4257dea8ed4b5b2d2f849ff444e9a646184bcb537", + "provenance_path": "tasks/16bda90956705b1aafcf7c24/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "438db0c531d8faf5512af23eae04dc4c6854dcf0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ca3ebbc9c4596e8d6e17eb7622cc5de93722b37c", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "task_sha256": "8e34d1cd7f0306cf8f96f1de62e1bb13aff3dda86e564fb9ee0d5e806ddbedc1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/instruction.md b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..25f6c420c095d250b2429e3bf5c56cf43d55c205 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/instruction.md @@ -0,0 +1,47 @@ +# TType.__setstate__ swaps T and S operators + +When using the glom library, I've encountered an issue with the TType.__setstate__ method. It appears that the T and S operators are being swapped during deserialization, causing unexpected behavior. + +## Description + +I'm using glom to transform and extract data from nested structures, but I'm getting errors when using the T and S operators. The issue seems to be in the TType.__setstate__ method where the mapping for 'T' and 'S' is reversed. + +Here's a simple reproduction case: + +```python +from glom import glom, T, S + +# This should work but fails +result = glom({}, (T.update({1: 1}), S.t)) + +# This also fails +target = {} +value = object() +default_struct = {'b': {'c': {}}} +glom.assign(target, 'a.b.c', value, missing=lambda: default_struct) +``` + +When running these examples, I get various errors like: +``` +glom.core.GlomError.wrap(IndexError): tuple index out of range +``` + +The issue appears to be in the TType.__setstate__ method where the mapping for 'T' and 'S' is swapped: + +``` +# Current problematic code (simplified) +self.__ops__ = ({'T': S, 'S': T, 'A': A}[state[0]],) + state[1:] + +# Should be +self.__ops__ = ({'T': T, 'S': S, 'A': A}[state[0]],) + state[1:] +``` + +This causes all sorts of issues with path access, assignments, and other operations that rely on the T and S operators. + +## Environment +- Python 3.10 +- glom latest version + +## 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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/metadata.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..a26c6a27183b10dd16b62d57f98f5302c8513b4f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_first", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_tutorial.py::test_tutorial" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "ca3ebbc9c4596e8d6e17eb7622cc5de93722b37c", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "438db0c531d8faf5512af23eae04dc4c6854dcf0" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_basic.py", + "glom/test/test_check.py", + "glom/test/test_cli.py", + "glom/test/test_error.py", + "glom/test/test_fill.py", + "glom/test/test_grouping.py", + "glom/test/test_match.py", + "glom/test/test_mutation.py", + "glom/test/test_path_and_t.py", + "glom/test/test_reduction.py", + "glom/test/test_scope_vars.py", + "glom/test/test_spec.py", + "glom/test/test_streaming.py", + "glom/test/test_target_types.py", + "glom/test/test_tutorial.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": [ + "glom/core.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1323667, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "6ebf72bda451a4c87b7790874147b3f0f295fc51ca0b4cfda9a7f2690329d650", + "is_fork": true, + "learner_path": "tasks/16bda90956705b1aafcf7c24/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/438db0c531d8faf5512af23eae04dc4c6854dcf0/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "0c7ec10234a0ebbc0754cba4257dea8ed4b5b2d2f849ff444e9a646184bcb537", + "provenance_path": "tasks/16bda90956705b1aafcf7c24/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "438db0c531d8faf5512af23eae04dc4c6854dcf0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ca3ebbc9c4596e8d6e17eb7622cc5de93722b37c", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "task_sha256": "8e34d1cd7f0306cf8f96f1de62e1bb13aff3dda86e564fb9ee0d5e806ddbedc1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/provenance.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f355c666a96beac35ce1575b437655d6c5575ffb --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "bb336f058f0332a12e3d35f5f0a2fe0d5dda9e428e41483c5141624783d2f63f", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/438db0c531d8faf5512af23eae04dc4c6854dcf0/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "54caab041f53c7a53c6a89725d74ef7f2eff9703a133c0691379fcf431a22a63", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "43c88db8eaae71e8a134240b2694bd259e9dc67eb7403401d2c4c06f79109d06", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "6ebf72bda451a4c87b7790874147b3f0f295fc51ca0b4cfda9a7f2690329d650", + "is_fork": true, + "learner_path": "tasks/16bda90956705b1aafcf7c24/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/438db0c531d8faf5512af23eae04dc4c6854dcf0/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "0c7ec10234a0ebbc0754cba4257dea8ed4b5b2d2f849ff444e9a646184bcb537", + "provenance_path": "tasks/16bda90956705b1aafcf7c24/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "438db0c531d8faf5512af23eae04dc4c6854dcf0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ca3ebbc9c4596e8d6e17eb7622cc5de93722b37c", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.combine_file__x7285apx", + "task_sha256": "8e34d1cd7f0306cf8f96f1de62e1bb13aff3dda86e564fb9ee0d5e806ddbedc1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..5f00e6a7be5aede7deaa06376962e9debf17d84d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/provided-gold.diff @@ -0,0 +1,190 @@ +diff --git a/glom/core.py b/glom/core.py +index 7ac756417bfbfccacbee13cd6ac2910c4d095b6f..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -1506,7 +1506,7 @@ + return tuple(({T: 'T', S: 'S', A: 'A'}[t_path[0]],) + t_path[1:]) + + def __setstate__(self, state): +- self.__ops__ = ({'T': S, 'S': T, 'A': A}[state[0]],) + state[1:] ++ self.__ops__ = ({'T': T, 'S': S, 'A': A}[state[0]],) + state[1:] + + + def _t_child(parent, operation, arg): +@@ -1529,117 +1529,130 @@ + try: + cur = scope[key] + except KeyError as e: +- err = PathAccessError(e, Path(_t), 1) # always only one level depth, hence 0 ++ err = PathAccessError(e, Path(_t), 0) # always only one level depth, hence 0 + if err: +- pass # silently swallow the error without raising +- return None ++ raise err ++ return cur + + + def _t_eval(target, _t, scope): + t_path = _t.__ops__ +- i = 0 ++ i = 1 + fetch_till = len(t_path) + root = t_path[0] + if root is T: ++ cur = target ++ elif root is S or root is A: ++ # A is basically the same as S, but last step is assign ++ if root is A: ++ fetch_till -= 2 ++ if fetch_till < 1: ++ raise BadSpec('cannot assign without destination') + cur = scope +- elif root is A or root is S: +- if root is S: +- fetch_till -= 1 +- if fetch_till < 1: +- pass +- cur = target +- if fetch_till > 1 and t_path[1] in ('P', '.'): +- cur = _s_first_magic(scope, t_path[2], _t) +- i += 1 +- elif root is A and fetch_till > 1 and t_path[1] == '(': ++ if fetch_till > 1 and t_path[1] in ('.', 'P'): ++ cur = _s_first_magic(cur, t_path[2], _t) ++ i += 2 ++ elif root is S and fetch_till > 1 and t_path[1] == '(': ++ # S(var='spec') style assignment + _, kwargs = t_path[2] +- target.update({ +- k: arg_val(scope, v, target) for k, v in kwargs.items()}) +- return scope ++ scope.update({ ++ k: arg_val(target, v, scope) for k, v in kwargs.items()}) ++ return target + + else: +- raise ValueError('TType instance with invalid root') ++ raise ValueError('TType instance with invalid root') # pragma: no cover + pae = None + while i < fetch_till: + op, arg = t_path[i], t_path[i + 1] +- arg = arg_val(cur, arg, scope) +- if op == '[': ++ arg = arg_val(target, arg, scope) ++ if op == '.': + try: + cur = getattr(cur, arg) + except AttributeError as e: + pae = PathAccessError(e, Path(_t), i // 2) +- elif op == '.': ++ elif op == '[': + try: + cur = cur[arg] + except (KeyError, IndexError, TypeError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op == 'P': ++ # Path type stuff (fuzzy match) + get = scope[TargetRegistry].get_handler('get', cur, path=t_path[2:i+2:2]) + try: +- cur = get(scope, arg) ++ cur = get(cur, arg) + except Exception as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op in 'xX': + nxt = [] + get_handler = scope[TargetRegistry].get_handler +- if op == 'X': ++ if op == 'x': # increases arity of cur each time through ++ # TODO: so many try/except -- could scope[TargetRegistry] stuff be cached on type? + _extend_children(nxt, cur, get_handler) +- elif op == 'x': ++ elif op == 'X': + sofar = set() + _extend_children(nxt, cur, get_handler) + for item in nxt: + if id(item) not in sofar: ++ sofar.add(id(item)) + _extend_children(nxt, item, get_handler) +- sofar.add(id(item)) ++ nxt.insert(0, cur) ++ # handle the rest of the t_path in recursive calls + cur = [] + todo = TType() + todo.__ops__ = (root,) + t_path[i+2:] + for child in nxt: + try: +- cur.append(_t_eval(todo, child, scope)) ++ cur.append(_t_eval(child, todo, scope)) + except PathAccessError: + pass +- continue ++ break # we handled the rest in recursive call, break loop + elif op == '(': + args, kwargs = arg + scope[Path] += t_path[2:i+2:2] + cur = scope[glom]( +- target, Call(cur, kwargs, args), scope) +- else: ++ target, Call(cur, args, kwargs), scope) ++ # call with target rather than cur, ++ # because it is probably more intuitive ++ # if args to the call "reset" their path ++ # e.g. "T.a" should mean the same thing ++ # in both of these specs: T.a and T.b(T.a) ++ else: # arithmetic operators + try: +- if op == '-': ++ if op == '+': + cur = cur + arg +- elif op == '+': ++ elif op == '-': ++ cur = cur - arg ++ elif op == '*': + cur = cur * arg +- elif op == '//': +- cur = cur - arg ++ #elif op == '#': ++ # cur = cur // arg # TODO: python 2 friendly approach? + elif op == '/': + cur = cur / arg + elif op == '%': +- cur = cur // arg ++ cur = cur % arg + elif op == ':': + cur = cur ** arg + elif op == '&': ++ cur = cur & arg ++ elif op == '|': ++ cur = cur | arg ++ elif op == '^': + cur = cur ^ arg +- elif op == '|': +- cur = cur & arg +- elif op == '^': +- cur = cur | arg + elif op == '~': + cur = ~cur + elif op == '_': + cur = -cur +- except (ZeroDivisionError, TypeError) as e: ++ except (TypeError, ZeroDivisionError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + if pae: +- return scope +- i += 1 +- if root is not A: ++ raise pae ++ i += 2 ++ if root is A: + op, arg = t_path[-2:] +- if cur is target: +- op = '[' +- _assign_op(dest=cur, op=op, arg=arg, val=scope, path=_t, scope=target) +- return scope ++ if cur is scope: ++ op = '[' # all assignment on scope is setitem ++ _assign_op(dest=cur, op=op, arg=arg, val=target, path=_t, scope=scope) ++ return target # A should not change the target + return cur + + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9695a4a25b1658cc7270e9dc4c90d33361314b4a --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/solution/solve.sh @@ -0,0 +1,196 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/core.py b/glom/core.py +index 7ac756417bfbfccacbee13cd6ac2910c4d095b6f..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -1506,7 +1506,7 @@ + return tuple(({T: 'T', S: 'S', A: 'A'}[t_path[0]],) + t_path[1:]) + + def __setstate__(self, state): +- self.__ops__ = ({'T': S, 'S': T, 'A': A}[state[0]],) + state[1:] ++ self.__ops__ = ({'T': T, 'S': S, 'A': A}[state[0]],) + state[1:] + + + def _t_child(parent, operation, arg): +@@ -1529,117 +1529,130 @@ + try: + cur = scope[key] + except KeyError as e: +- err = PathAccessError(e, Path(_t), 1) # always only one level depth, hence 0 ++ err = PathAccessError(e, Path(_t), 0) # always only one level depth, hence 0 + if err: +- pass # silently swallow the error without raising +- return None ++ raise err ++ return cur + + + def _t_eval(target, _t, scope): + t_path = _t.__ops__ +- i = 0 ++ i = 1 + fetch_till = len(t_path) + root = t_path[0] + if root is T: ++ cur = target ++ elif root is S or root is A: ++ # A is basically the same as S, but last step is assign ++ if root is A: ++ fetch_till -= 2 ++ if fetch_till < 1: ++ raise BadSpec('cannot assign without destination') + cur = scope +- elif root is A or root is S: +- if root is S: +- fetch_till -= 1 +- if fetch_till < 1: +- pass +- cur = target +- if fetch_till > 1 and t_path[1] in ('P', '.'): +- cur = _s_first_magic(scope, t_path[2], _t) +- i += 1 +- elif root is A and fetch_till > 1 and t_path[1] == '(': ++ if fetch_till > 1 and t_path[1] in ('.', 'P'): ++ cur = _s_first_magic(cur, t_path[2], _t) ++ i += 2 ++ elif root is S and fetch_till > 1 and t_path[1] == '(': ++ # S(var='spec') style assignment + _, kwargs = t_path[2] +- target.update({ +- k: arg_val(scope, v, target) for k, v in kwargs.items()}) +- return scope ++ scope.update({ ++ k: arg_val(target, v, scope) for k, v in kwargs.items()}) ++ return target + + else: +- raise ValueError('TType instance with invalid root') ++ raise ValueError('TType instance with invalid root') # pragma: no cover + pae = None + while i < fetch_till: + op, arg = t_path[i], t_path[i + 1] +- arg = arg_val(cur, arg, scope) +- if op == '[': ++ arg = arg_val(target, arg, scope) ++ if op == '.': + try: + cur = getattr(cur, arg) + except AttributeError as e: + pae = PathAccessError(e, Path(_t), i // 2) +- elif op == '.': ++ elif op == '[': + try: + cur = cur[arg] + except (KeyError, IndexError, TypeError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op == 'P': ++ # Path type stuff (fuzzy match) + get = scope[TargetRegistry].get_handler('get', cur, path=t_path[2:i+2:2]) + try: +- cur = get(scope, arg) ++ cur = get(cur, arg) + except Exception as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op in 'xX': + nxt = [] + get_handler = scope[TargetRegistry].get_handler +- if op == 'X': ++ if op == 'x': # increases arity of cur each time through ++ # TODO: so many try/except -- could scope[TargetRegistry] stuff be cached on type? + _extend_children(nxt, cur, get_handler) +- elif op == 'x': ++ elif op == 'X': + sofar = set() + _extend_children(nxt, cur, get_handler) + for item in nxt: + if id(item) not in sofar: ++ sofar.add(id(item)) + _extend_children(nxt, item, get_handler) +- sofar.add(id(item)) ++ nxt.insert(0, cur) ++ # handle the rest of the t_path in recursive calls + cur = [] + todo = TType() + todo.__ops__ = (root,) + t_path[i+2:] + for child in nxt: + try: +- cur.append(_t_eval(todo, child, scope)) ++ cur.append(_t_eval(child, todo, scope)) + except PathAccessError: + pass +- continue ++ break # we handled the rest in recursive call, break loop + elif op == '(': + args, kwargs = arg + scope[Path] += t_path[2:i+2:2] + cur = scope[glom]( +- target, Call(cur, kwargs, args), scope) +- else: ++ target, Call(cur, args, kwargs), scope) ++ # call with target rather than cur, ++ # because it is probably more intuitive ++ # if args to the call "reset" their path ++ # e.g. "T.a" should mean the same thing ++ # in both of these specs: T.a and T.b(T.a) ++ else: # arithmetic operators + try: +- if op == '-': ++ if op == '+': + cur = cur + arg +- elif op == '+': ++ elif op == '-': ++ cur = cur - arg ++ elif op == '*': + cur = cur * arg +- elif op == '//': +- cur = cur - arg ++ #elif op == '#': ++ # cur = cur // arg # TODO: python 2 friendly approach? + elif op == '/': + cur = cur / arg + elif op == '%': +- cur = cur // arg ++ cur = cur % arg + elif op == ':': + cur = cur ** arg + elif op == '&': ++ cur = cur & arg ++ elif op == '|': ++ cur = cur | arg ++ elif op == '^': + cur = cur ^ arg +- elif op == '|': +- cur = cur & arg +- elif op == '^': +- cur = cur | arg + elif op == '~': + cur = ~cur + elif op == '_': + cur = -cur +- except (ZeroDivisionError, TypeError) as e: ++ except (TypeError, ZeroDivisionError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + if pae: +- return scope +- i += 1 +- if root is not A: ++ raise pae ++ i += 2 ++ if root is A: + op, arg = t_path[-2:] +- if cur is target: +- op = '[' +- _assign_op(dest=cur, op=op, arg=arg, val=scope, path=_t, scope=target) +- return scope ++ if cur is scope: ++ op = '[' # all assignment on scope is setitem ++ _assign_op(dest=cur, op=op, arg=arg, val=target, path=_t, scope=scope) ++ return target # A should not change the target + return cur + + +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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/task.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..57c7e7f58fdc7ca934f19cf169266f7408bed702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:4a5d60a897fe0c9aa95dcba5e8a813900e101edd1e09767d41faa2fdd57e9399" +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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..25e1390e64bf22cdebb275a1cc09bf25d2ab2c4f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_first", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_tutorial.py::test_tutorial" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..aac3335d1b161591d73edda63fdcff1f3a543554 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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/glom/core.py b/glom/core.py +index 7ac756417bfbfccacbee13cd6ac2910c4d095b6f..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -1506,7 +1506,7 @@ + return tuple(({T: 'T', S: 'S', A: 'A'}[t_path[0]],) + t_path[1:]) + + def __setstate__(self, state): +- self.__ops__ = ({'T': S, 'S': T, 'A': A}[state[0]],) + state[1:] ++ self.__ops__ = ({'T': T, 'S': S, 'A': A}[state[0]],) + state[1:] + + + def _t_child(parent, operation, arg): +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/mahmoud__glom.fb3c4e76.combine_file__x7285apx/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.combine_file__x7285apx/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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..a8a99d629c4167ff652733e0411a6b317515d48d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "c2c1b7e398373975c56c3e84aa148867968507c9c3a06700687ddc4ea6024483", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "319d82270ccb732d2b102df0850c9112c83da906514b6a372e06b7bc9f7efa1c", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "2ed2b8cb323488d9f4709b558b0f28b90e674efc", + "source_completion_sha256": "5a9805292a6db3cb083e9bb56bace0452f611cfb5f4d3c54ace2e4de28d9f30a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "073f100c7c3eac38525cd8783d3571a9aec893f858770dd34306cd5ae7fa2f0e", + "is_fork": true, + "learner_path": "tasks/a2ea1f053f7ac9cb95cf5429/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/2ed2b8cb323488d9f4709b558b0f28b90e674efc/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "6ff3c2f90d16f32f90f138e0f317831d9f80630e49600076d9c00bcc178760ee", + "provenance_path": "tasks/a2ea1f053f7ac9cb95cf5429/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2ed2b8cb323488d9f4709b558b0f28b90e674efc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b73c4112c6df26432e5fb7639eafded25d609492", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "task_sha256": "d7144e09132c7d687871953d9ba9bb88d65d77ffffdbe99a952cd03c2801f015", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b575ff5150ee5088432ef0653ecdfd13484767b5 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/instruction.md @@ -0,0 +1,26 @@ +bbformat function breaks with string formatting conversion specifiers + +#### Description + +The `bbformat` function in glom's core module fails when using string formatting conversion specifiers like `{0!r}`. The function appears to have issues with both the quote escaping logic and argument order in the parent class method call. + +#### Steps/Code to Reproduce + +```python +from glom.core import bbformat + +# This should work but raises ValueError +bbformat('{0!r}', 'test') +``` + +#### Expected vs Actual Behavior + +Expected: The function should format the string properly with repr conversion, similar to how standard string formatting works. + +Actual: Raises `ValueError: Unknown conversion type` due to incorrect argument order being passed to the parent formatter method. + +The issue appears to be in the `_BBReprFormatter.convert_field` method where arguments are passed in the wrong order to the parent class, and the quote replacement logic may also be incorrect. + +## 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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..bc0465206529f4d8cef627edbb84087e3f7dce27 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_match.py::test_check_ported_tests" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "b73c4112c6df26432e5fb7639eafded25d609492", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "2ed2b8cb323488d9f4709b558b0f28b90e674efc" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_basic.py", + "glom/test/test_error.py", + "glom/test/test_match.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": [ + "glom/core.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1381160, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "073f100c7c3eac38525cd8783d3571a9aec893f858770dd34306cd5ae7fa2f0e", + "is_fork": true, + "learner_path": "tasks/a2ea1f053f7ac9cb95cf5429/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/2ed2b8cb323488d9f4709b558b0f28b90e674efc/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "6ff3c2f90d16f32f90f138e0f317831d9f80630e49600076d9c00bcc178760ee", + "provenance_path": "tasks/a2ea1f053f7ac9cb95cf5429/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2ed2b8cb323488d9f4709b558b0f28b90e674efc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b73c4112c6df26432e5fb7639eafded25d609492", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "task_sha256": "d7144e09132c7d687871953d9ba9bb88d65d77ffffdbe99a952cd03c2801f015", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..dcb9016404522b7f3e09f8991cfde38535135245 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c2c1b7e398373975c56c3e84aa148867968507c9c3a06700687ddc4ea6024483", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/2ed2b8cb323488d9f4709b558b0f28b90e674efc/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "5a9805292a6db3cb083e9bb56bace0452f611cfb5f4d3c54ace2e4de28d9f30a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "235ff1a2a20c6572c0feb55d05a36eb1c1a4b960ec3f593c92d6b5403cee4031", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "073f100c7c3eac38525cd8783d3571a9aec893f858770dd34306cd5ae7fa2f0e", + "is_fork": true, + "learner_path": "tasks/a2ea1f053f7ac9cb95cf5429/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/2ed2b8cb323488d9f4709b558b0f28b90e674efc/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "6ff3c2f90d16f32f90f138e0f317831d9f80630e49600076d9c00bcc178760ee", + "provenance_path": "tasks/a2ea1f053f7ac9cb95cf5429/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2ed2b8cb323488d9f4709b558b0f28b90e674efc", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b73c4112c6df26432e5fb7639eafded25d609492", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0frk4okw", + "task_sha256": "d7144e09132c7d687871953d9ba9bb88d65d77ffffdbe99a952cd03c2801f015", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..d75831cedb6adf3b39f86c5859d0c6ae0e3b06bd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/provided-gold.diff @@ -0,0 +1,15 @@ +diff --git a/glom/core.py b/glom/core.py +index ab1cfaa6cca98a80948a67b5fde9390d1024dcf5..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -535,8 +535,8 @@ + """ + def convert_field(self, value, conversion): + if conversion == 'r': +- return bbrepr(value).replace("'", "\\'") +- return super().convert_field(conversion, value) ++ return bbrepr(value).replace("\\'", "'") ++ return super().convert_field(value, conversion) + + + bbformat = _BBReprFormatter().format diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c983e747318e53ce13e7a4f3b9a3139bbe97f4dd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/solution/solve.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/core.py b/glom/core.py +index ab1cfaa6cca98a80948a67b5fde9390d1024dcf5..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -535,8 +535,8 @@ + """ + def convert_field(self, value, conversion): + if conversion == 'r': +- return bbrepr(value).replace("'", "\\'") +- return super().convert_field(conversion, value) ++ return bbrepr(value).replace("\\'", "'") ++ return super().convert_field(value, conversion) + + + bbformat = _BBReprFormatter().format +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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47f091397b4a00d45ebda5cd886d079a3bbc9d91 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:2373aec60ce6125239e015a4e392a21318146e013457ef9134b5a6beb45d761e" +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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..c916ecb53c31cc3ff14c45521df25f41d3d975a7 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_match.py::test_check_ported_tests" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0frk4okw/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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..0910a01229fb8b2b39220c1838626a3a63e8f576 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "760d19f513b8cf3660af266ccf02ef7127c9cbf2167baae282538aaff55ac146", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "14873dcbb6104a31984145628d7142a00295c14a97ebad604a3b58bbc7b13743", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "6a1ae8d12939e5a7a437689cb4625bf54bb04090", + "source_completion_sha256": "a3ac587e9b4b99fefe2200851abffba33728ea5ca81fbdc112eb235ba5622c0e", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "678bbc386a60152cee35d40619d1c35872dee09d09a68f4a31d9fb4f2fb461af", + "is_fork": true, + "learner_path": "tasks/057775c77d2f9223d15d87e7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6a1ae8d12939e5a7a437689cb4625bf54bb04090/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3f46d7bae58785a73f7b752d266cf404ec72fc15b5e99b2fd7e0d5734795ccf7", + "provenance_path": "tasks/057775c77d2f9223d15d87e7/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6a1ae8d12939e5a7a437689cb4625bf54bb04090", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bc7fec30c0d2d7a783dbaa1a525176ecc6e0e2a9", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "task_sha256": "fb606f1ab2ec56b674f6a64a2ef350ade0cc37db7a3fd7de50d3074c2075d10e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb6bbc85962ccc03b1f1e49e876992416efe6f0f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/instruction.md @@ -0,0 +1,27 @@ +S magic returns None instead of raising PathAccessError on missing keys + +#### Description + +When using the S magic syntax to access missing keys in scope, the function now returns None instead of raising a PathAccessError as expected. + +#### Steps/Code to Reproduce + +```python +from glom import glom, S + +# This should raise PathAccessError but returns None instead +result = glom({}, S.missing_key) +print(f"Result: {result}") # prints: Result: None +# Expected: PathAccessError should be raised + +# Another example with nested access +result = glom({'a': {}}, S.a.missing_nested_key) +print(f"Result: {result}") # prints: Result: None +# Expected: PathAccessError should be raised +``` + +The S magic syntax is supposed to raise PathAccessError when trying to access keys that don't exist in the scope, but it's now silently returning None instead of properly propagating the error. + +## 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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5f7923dd04444aa0f8fd951dbe6f384d28b0ec7a --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "bc7fec30c0d2d7a783dbaa1a525176ecc6e0e2a9", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "6a1ae8d12939e5a7a437689cb4625bf54bb04090" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_match.py", + "glom/test/test_path_and_t.py", + "glom/test/test_scope_vars.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": [ + "glom/core.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1399271, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "678bbc386a60152cee35d40619d1c35872dee09d09a68f4a31d9fb4f2fb461af", + "is_fork": true, + "learner_path": "tasks/057775c77d2f9223d15d87e7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6a1ae8d12939e5a7a437689cb4625bf54bb04090/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3f46d7bae58785a73f7b752d266cf404ec72fc15b5e99b2fd7e0d5734795ccf7", + "provenance_path": "tasks/057775c77d2f9223d15d87e7/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6a1ae8d12939e5a7a437689cb4625bf54bb04090", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bc7fec30c0d2d7a783dbaa1a525176ecc6e0e2a9", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "task_sha256": "fb606f1ab2ec56b674f6a64a2ef350ade0cc37db7a3fd7de50d3074c2075d10e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..9db34867ccd10bcc9ce895e7e406d24a756a100a --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "760d19f513b8cf3660af266ccf02ef7127c9cbf2167baae282538aaff55ac146", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6a1ae8d12939e5a7a437689cb4625bf54bb04090/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "a3ac587e9b4b99fefe2200851abffba33728ea5ca81fbdc112eb235ba5622c0e", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f51096933037ed817644231339dd6cf6325242ebed7a1d51043be55fb8349523", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "678bbc386a60152cee35d40619d1c35872dee09d09a68f4a31d9fb4f2fb461af", + "is_fork": true, + "learner_path": "tasks/057775c77d2f9223d15d87e7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/6a1ae8d12939e5a7a437689cb4625bf54bb04090/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3f46d7bae58785a73f7b752d266cf404ec72fc15b5e99b2fd7e0d5734795ccf7", + "provenance_path": "tasks/057775c77d2f9223d15d87e7/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6a1ae8d12939e5a7a437689cb4625bf54bb04090", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bc7fec30c0d2d7a783dbaa1a525176ecc6e0e2a9", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0", + "task_sha256": "fb606f1ab2ec56b674f6a64a2ef350ade0cc37db7a3fd7de50d3074c2075d10e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..52b0a0539457965aa00d9e2362636abf836c4390 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/provided-gold.diff @@ -0,0 +1,18 @@ +diff --git a/glom/core.py b/glom/core.py +index 30f1cef36ed2c5b7c435be8830ce9335565e7dc2..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -1529,10 +1529,10 @@ + try: + cur = scope[key] + except KeyError as e: +- err = PathAccessError(e, Path(_t), 1) # always only one level depth, hence 0 ++ err = PathAccessError(e, Path(_t), 0) # always only one level depth, hence 0 + if err: +- pass # silently swallow the error without raising +- return None ++ raise err ++ return cur + + + def _t_eval(target, _t, scope): diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4c3fb3cf6593710c786416cefbab39aeab6dc53f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/solution/solve.sh @@ -0,0 +1,24 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/core.py b/glom/core.py +index 30f1cef36ed2c5b7c435be8830ce9335565e7dc2..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -1529,10 +1529,10 @@ + try: + cur = scope[key] + except KeyError as e: +- err = PathAccessError(e, Path(_t), 1) # always only one level depth, hence 0 ++ err = PathAccessError(e, Path(_t), 0) # always only one level depth, hence 0 + if err: +- pass # silently swallow the error without raising +- return None ++ raise err ++ return cur + + + def _t_eval(target, _t, scope): +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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..05ac8ab88b060c84345d2244714e3af8e9b767de --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:c03faf60e81a0e3c395fd736e2649d27612101890a24f5141d6a2046376d4f14" +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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..10b1c73a82b5ca2cab2652e8b38082d2809b2652 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n4ho2l0/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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..8393cbd32bd4db281ecd4162c72e7867563181a7 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "af41713690c88a2840f4d4c5f43503bcc7fa8fb64ea30755edcb837fd2122188", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "f8593581ea0724c981192002a481039eed5bbbbe81d68a6a289e2b52cf970b67", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "f2219e0a9cac9300f648d5f92bec60e2a153aeae", + "source_completion_sha256": "862f5f3384908469adc30f5fe0d0f29c295f6b3bf4e0116abe7ce3446cfa649f", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "47c83fe60ba40bfb3d0cf2074bdba6e4d84734fd7972c474543183b0255b42cf", + "is_fork": true, + "learner_path": "tasks/cf7390eb141a985dcbf74f11/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f2219e0a9cac9300f648d5f92bec60e2a153aeae/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "23483c391c25d3f52b575f79a9c666fb7e628529720cc3271bcdd1bcc555c06b", + "provenance_path": "tasks/cf7390eb141a985dcbf74f11/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f2219e0a9cac9300f648d5f92bec60e2a153aeae", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "40a119e8ec46b0b701f069a40fa0d93adfbe28c7", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "task_sha256": "79b322822ab6b32807e07bd40f2c57f5baf1b56948efe862684c7a26420bbd81", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3583b9d3862a43b7a7761690a8454ba203dd904d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/instruction.md @@ -0,0 +1,27 @@ +OR operator precedence reversed in matching expressions + +When using the OR operator (`|`) with matching expressions, the operands are being evaluated in reverse order, causing unexpected behavior in conditional logic. + +#### Steps/Code to Reproduce + +```python +from glom import glom, M, Val, SKIP + +# This should return [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] +# but instead returns [7, 7, 7, 7, 7, 7, 7, 7, 7, 7] +result = glom(range(10), [(M < 7) | Val(7)]) +print("Expected: [0, 1, 2, 3, 4, 5, 6, 7, 7, 7]") +print("Actual: ", result) + +# This should return [0, 1, 2, 3, 4, 5, 6] +# but instead returns [] +result2 = glom(range(10), [(M < 7) | Val(SKIP)]) +print("Expected: [0, 1, 2, 3, 4, 5, 6]") +print("Actual: ", result2) +``` + +The OR operator appears to be evaluating the right operand first instead of the left operand, which breaks the expected short-circuit evaluation behavior where `(M < 7)` should be checked first, and only if it fails should `Val(7)` or `Val(SKIP)` be used as fallback. + +## 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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..3f52ee345201fa3fa9c0c57c4067af1c0a101600 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_match.py::test_clamp" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "40a119e8ec46b0b701f069a40fa0d93adfbe28c7", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "f2219e0a9cac9300f648d5f92bec60e2a153aeae" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_match.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": [ + "glom/matching.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1412692, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "47c83fe60ba40bfb3d0cf2074bdba6e4d84734fd7972c474543183b0255b42cf", + "is_fork": true, + "learner_path": "tasks/cf7390eb141a985dcbf74f11/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f2219e0a9cac9300f648d5f92bec60e2a153aeae/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "23483c391c25d3f52b575f79a9c666fb7e628529720cc3271bcdd1bcc555c06b", + "provenance_path": "tasks/cf7390eb141a985dcbf74f11/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f2219e0a9cac9300f648d5f92bec60e2a153aeae", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "40a119e8ec46b0b701f069a40fa0d93adfbe28c7", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "task_sha256": "79b322822ab6b32807e07bd40f2c57f5baf1b56948efe862684c7a26420bbd81", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..b104ce41fdd7079f709840f487466be3e00e7d27 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "af41713690c88a2840f4d4c5f43503bcc7fa8fb64ea30755edcb837fd2122188", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f2219e0a9cac9300f648d5f92bec60e2a153aeae/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "862f5f3384908469adc30f5fe0d0f29c295f6b3bf4e0116abe7ce3446cfa649f", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "be8bc56a8f51c21f3fb7634f874df7f16bbfea41ea0078c549104315dfa1fc75", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "47c83fe60ba40bfb3d0cf2074bdba6e4d84734fd7972c474543183b0255b42cf", + "is_fork": true, + "learner_path": "tasks/cf7390eb141a985dcbf74f11/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/f2219e0a9cac9300f648d5f92bec60e2a153aeae/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "23483c391c25d3f52b575f79a9c666fb7e628529720cc3271bcdd1bcc555c06b", + "provenance_path": "tasks/cf7390eb141a985dcbf74f11/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f2219e0a9cac9300f648d5f92bec60e2a153aeae", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "40a119e8ec46b0b701f069a40fa0d93adfbe28c7", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0n76829i", + "task_sha256": "79b322822ab6b32807e07bd40f2c57f5baf1b56948efe862684c7a26420bbd81", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..fd54eac1b2fc99e4c8e546f7e8ada90217c2f866 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/glom/matching.py b/glom/matching.py +index 1b676888b1beda20fce36a8981214c78396ea1cc..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -433,7 +433,7 @@ + __rand__ = __and__ + + def __or__(self, other): +- return Or(other, self) ++ return Or(self, other) + + def __invert__(self): + return Not(self) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..10e0c84ca7d1cadc6f8cd6339848ffdb9b0536b1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/matching.py b/glom/matching.py +index 1b676888b1beda20fce36a8981214c78396ea1cc..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -433,7 +433,7 @@ + __rand__ = __and__ + + def __or__(self, other): +- return Or(other, self) ++ return Or(self, other) + + def __invert__(self): + return Not(self) +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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b6175e915234e7e3cee76ada50339bc9a0cc74af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ae3a1833c9bbc26126bedf0c8a987f260de7461702d9827d4f0a3b6c772cfeb2" +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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..0d243eaabbfe0fa07957866b90cbff1be429b79f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_match.py::test_clamp" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0n76829i/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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..2a9a1831f4c8aeda3d988cfc5fb6eb93b87dd4c7 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "0a7670bd2c682e93408054381e6af13a2472cb6363d8d466a6be531db155785a", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "96f007f388006ef72e951760bb3c870904db1bb786a2e7e2d02f8fe051d4e6a7", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "288528627788ecafb6f675aba2a8a6313bfe41be", + "source_completion_sha256": "7e5c39774d3f86a8b8cda44517a6ee0800e1aacc8a16326708daa888e6870329", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "3db16b2cd4f1d9bdfd0b4314093787f01c8b311e036b1db9568f17d6524e2b50", + "is_fork": true, + "learner_path": "tasks/6d5a09bfd69c86833ca59d2b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/288528627788ecafb6f675aba2a8a6313bfe41be/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "41a7caafd181eabef5ce71ba4f3938b43b2bdeb7ab3d81bbb3874309052b229a", + "provenance_path": "tasks/6d5a09bfd69c86833ca59d2b/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "288528627788ecafb6f675aba2a8a6313bfe41be", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6ed2dc690f7810e6fa1feff7b0ad6cc0b204bbbe", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "task_sha256": "29d708ff779d0e5aec4356872fade47a48137e78c5a218a9aceac1c536374898", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ab4a0e93ed955900c55593c430f734c80bd3c9c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/instruction.md @@ -0,0 +1,23 @@ +Path creation from string broken with reversed segments + +When creating a Path from a string using `Path.from_text()`, the path segments are being processed in reverse order, causing path access to fail. + +#### Steps to Reproduce + +```python +from glom import Path, glom + +# This should work but fails +target = {'a': {'b': 'value'}} +path = Path.from_text('a.b') +result = glom(target, path) +print(result) # Should print 'value' but raises PathAccessError +``` + +The issue appears when PATH_STAR is disabled (which seems to be the default in some configurations). The path segments get reversed during creation, so `'a.b'` becomes equivalent to `Path('b', 'a')` instead of `Path('a', 'b')`. + +This affects basic path operations and makes simple nested access patterns fail unexpectedly. + +## 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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9b33a2a98986dce88b494ac35cee9a0fba21d188 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_tutorial.py::test_tutorial" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "6ed2dc690f7810e6fa1feff7b0ad6cc0b204bbbe", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "288528627788ecafb6f675aba2a8a6313bfe41be" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_basic.py", + "glom/test/test_check.py", + "glom/test/test_cli.py", + "glom/test/test_error.py", + "glom/test/test_fill.py", + "glom/test/test_grouping.py", + "glom/test/test_match.py", + "glom/test/test_mutation.py", + "glom/test/test_path_and_t.py", + "glom/test/test_reduction.py", + "glom/test/test_scope_vars.py", + "glom/test/test_target_types.py", + "glom/test/test_tutorial.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": [ + "glom/core.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1331958, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "3db16b2cd4f1d9bdfd0b4314093787f01c8b311e036b1db9568f17d6524e2b50", + "is_fork": true, + "learner_path": "tasks/6d5a09bfd69c86833ca59d2b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/288528627788ecafb6f675aba2a8a6313bfe41be/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "41a7caafd181eabef5ce71ba4f3938b43b2bdeb7ab3d81bbb3874309052b229a", + "provenance_path": "tasks/6d5a09bfd69c86833ca59d2b/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "288528627788ecafb6f675aba2a8a6313bfe41be", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6ed2dc690f7810e6fa1feff7b0ad6cc0b204bbbe", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "task_sha256": "29d708ff779d0e5aec4356872fade47a48137e78c5a218a9aceac1c536374898", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..6d28b195963c26161611df695a5c107d2a214503 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "0a7670bd2c682e93408054381e6af13a2472cb6363d8d466a6be531db155785a", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/288528627788ecafb6f675aba2a8a6313bfe41be/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "7e5c39774d3f86a8b8cda44517a6ee0800e1aacc8a16326708daa888e6870329", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "08260f1edd340e75f1cc673b2fad3534fb99b2f9d75ac373249b1e4e64fb271f", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "3db16b2cd4f1d9bdfd0b4314093787f01c8b311e036b1db9568f17d6524e2b50", + "is_fork": true, + "learner_path": "tasks/6d5a09bfd69c86833ca59d2b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/288528627788ecafb6f675aba2a8a6313bfe41be/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "41a7caafd181eabef5ce71ba4f3938b43b2bdeb7ab3d81bbb3874309052b229a", + "provenance_path": "tasks/6d5a09bfd69c86833ca59d2b/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "288528627788ecafb6f675aba2a8a6313bfe41be", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6ed2dc690f7810e6fa1feff7b0ad6cc0b204bbbe", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0p95nibl", + "task_sha256": "29d708ff779d0e5aec4356872fade47a48137e78c5a218a9aceac1c536374898", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..89694f34f3c84147a42ed39ba1fbc7c9d3675ca8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/provided-gold.diff @@ -0,0 +1,29 @@ +diff --git a/glom/core.py b/glom/core.py +index 7f8242d2d4a80968221ecdcf9415a5c679bd44c6..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -648,18 +648,18 @@ + """ + def create(): + segs = text.split('.') +- if not PATH_STAR: ++ if PATH_STAR: + segs = [ + _T_STAR if seg == '*' else + _T_STARSTAR if seg == '**' else seg +- for seg in reversed(segs)] +- elif cls._STAR_WARNED: +- if '*' not in segs and '**' not in segs: ++ for seg in segs] ++ elif not cls._STAR_WARNED: ++ if '*' in segs or '**' in segs: + warnings.warn( + "'*' and '**' have changed behavior in glom version 23.1." + " Recommend switch to T['*'] or T['**'].") +- cls._STAR_WARNED = False +- return cls(segs) ++ cls._STAR_WARNED = True ++ return cls(*segs) + + cache = cls._CACHE[PATH_STAR] # remove this when PATH_STAR is default + if text not in cache: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..389b3993e6cf333204bf57b169ada06e00d14717 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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/glom/core.py b/glom/core.py +index 7f8242d2d4a80968221ecdcf9415a5c679bd44c6..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -648,18 +648,18 @@ + """ + def create(): + segs = text.split('.') +- if not PATH_STAR: ++ if PATH_STAR: + segs = [ + _T_STAR if seg == '*' else + _T_STARSTAR if seg == '**' else seg +- for seg in reversed(segs)] +- elif cls._STAR_WARNED: +- if '*' not in segs and '**' not in segs: ++ for seg in segs] ++ elif not cls._STAR_WARNED: ++ if '*' in segs or '**' in segs: + warnings.warn( + "'*' and '**' have changed behavior in glom version 23.1." + " Recommend switch to T['*'] or T['**'].") +- cls._STAR_WARNED = False +- return cls(segs) ++ cls._STAR_WARNED = True ++ return cls(*segs) + + cache = cls._CACHE[PATH_STAR] # remove this when PATH_STAR is default + if text not in cache: +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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd1eaae430fc4e702eb2797776b031bfc4a0043c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:3f122836df5f0de3dc58fa9db1f070ef9ab11d37580c0c72d4ab1096d69da9be" +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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..7ad6d6d2f39e66ee4fdc8b75a432f07e078d0be9 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_tutorial.py::test_tutorial" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0p95nibl/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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..84314f9524f45e70d608377b88163c49de9b068d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "7ea6e21f897dae192c0498acafc37be34ceebf1857f46f84abf196a47529d810", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "30f233ce772f1640acd6ea6c732c209ecb50a5a3aeea1d706919f84b0efdc26d", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "71b03ac5c1d6e09a884678248e3950ec3579ee32", + "source_completion_sha256": "d73d036b3b339b33ca559740dd8772e858dee0da3e0ca478ea67f617e56838ca", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "088db359edd87733a4f60f60233bda9918087c42581db077fdeca659934e3206", + "is_fork": true, + "learner_path": "tasks/1ba3ee9149eaa27c6b60c197/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/71b03ac5c1d6e09a884678248e3950ec3579ee32/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "03da0233c0f0536b83f44a51831e17fae884765a812b7db645d967ae0f33e808", + "provenance_path": "tasks/1ba3ee9149eaa27c6b60c197/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "71b03ac5c1d6e09a884678248e3950ec3579ee32", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "89ef384b7adb89a8f2453bbe49baf75101b02402", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "task_sha256": "2c873ccea541539991dfd82dcc1843600edb81e9e5a3087dabb81e659cc785ff", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7da60889c3074b399032c767efaad899dcbe9eb --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/instruction.md @@ -0,0 +1,32 @@ +M() accepts invalid specs without proper validation + +When using `M()` to wrap subspecs for comparison operations, invalid specs are silently accepted instead of raising a `TypeError`. This causes unexpected behavior where the matching logic fails to work correctly. + +#### Steps/Code to Reproduce + +```python +from glom import glom, M, T + +# This should raise TypeError but doesn't +try: + result = M('failure') # String is not a valid T-style spec + print("No error raised - this is wrong!") +except TypeError as e: + print(f"Expected error: {e}") + +# This also demonstrates the issue in practice +target = {'a': 1, 'b': 2} +spec = M(T['a']) < M(T['b']) # This should work +result = glom(target, spec) +print(f"Valid spec result: {result}") + +# But invalid specs don't get caught +invalid_spec = M('not_a_spec') # This should fail but doesn't +print(f"Invalid spec created: {invalid_spec}") +``` + +The issue appears to be that `M()` is not properly validating that the provided spec is a T-style spec before wrapping it, allowing invalid specifications to pass through the validation step. + +## 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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..0a5d764ea101fd940581fcedf2b44bfe83f2522c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_scope_vars.py::test_max_skip" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "89ef384b7adb89a8f2453bbe49baf75101b02402", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "71b03ac5c1d6e09a884678248e3950ec3579ee32" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_match.py", + "glom/test/test_scope_vars.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": [ + "glom/matching.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1409132, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "088db359edd87733a4f60f60233bda9918087c42581db077fdeca659934e3206", + "is_fork": true, + "learner_path": "tasks/1ba3ee9149eaa27c6b60c197/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/71b03ac5c1d6e09a884678248e3950ec3579ee32/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "03da0233c0f0536b83f44a51831e17fae884765a812b7db645d967ae0f33e808", + "provenance_path": "tasks/1ba3ee9149eaa27c6b60c197/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "71b03ac5c1d6e09a884678248e3950ec3579ee32", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "89ef384b7adb89a8f2453bbe49baf75101b02402", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "task_sha256": "2c873ccea541539991dfd82dcc1843600edb81e9e5a3087dabb81e659cc785ff", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a44fdafde2f5f5ed29eeceb1e352695a1238b114 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "7ea6e21f897dae192c0498acafc37be34ceebf1857f46f84abf196a47529d810", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/71b03ac5c1d6e09a884678248e3950ec3579ee32/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "d73d036b3b339b33ca559740dd8772e858dee0da3e0ca478ea67f617e56838ca", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "be9755101136bc7a7ae5df09083f8c3775ac965fa475da03f393f5d6f1534a98", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "088db359edd87733a4f60f60233bda9918087c42581db077fdeca659934e3206", + "is_fork": true, + "learner_path": "tasks/1ba3ee9149eaa27c6b60c197/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/71b03ac5c1d6e09a884678248e3950ec3579ee32/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "03da0233c0f0536b83f44a51831e17fae884765a812b7db645d967ae0f33e808", + "provenance_path": "tasks/1ba3ee9149eaa27c6b60c197/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "71b03ac5c1d6e09a884678248e3950ec3579ee32", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "89ef384b7adb89a8f2453bbe49baf75101b02402", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z", + "task_sha256": "2c873ccea541539991dfd82dcc1843600edb81e9e5a3087dabb81e659cc785ff", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..5081e1b3d4e4233ff510aed4d1edf6401fc757c0 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/provided-gold.diff @@ -0,0 +1,17 @@ +diff --git a/glom/matching.py b/glom/matching.py +index 18f1729e8f735ce86dcc05402cb5259a571c356e..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -521,8 +521,10 @@ + def __call__(self, spec): + """wrap a sub-spec in order to apply comparison operators to the result""" + if not isinstance(spec, type(T)): +- pass # Swallow the exception, allowing invalid specs to pass through +- return _MSubspec(None) # Pass None instead of the actual spec ++ # TODO: open this up for other specs so we can do other ++ # checks, like function calls ++ raise TypeError("M() only accepts T-style specs, not %s" % type(spec).__name__) ++ return _MSubspec(spec) + + def __eq__(self, other): + return _MExpr(self, '=', other) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..40eb9fc9aa2809553cdb497e85b5adcaac44e3a1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/solution/solve.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/matching.py b/glom/matching.py +index 18f1729e8f735ce86dcc05402cb5259a571c356e..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -521,8 +521,10 @@ + def __call__(self, spec): + """wrap a sub-spec in order to apply comparison operators to the result""" + if not isinstance(spec, type(T)): +- pass # Swallow the exception, allowing invalid specs to pass through +- return _MSubspec(None) # Pass None instead of the actual spec ++ # TODO: open this up for other specs so we can do other ++ # checks, like function calls ++ raise TypeError("M() only accepts T-style specs, not %s" % type(spec).__name__) ++ return _MSubspec(spec) + + def __eq__(self, other): + return _MExpr(self, '=', other) +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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d6ee8761a00e2e1dce2a975e4f3474661627db3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:6b0204707e357fdb3197593ad97f20a64052d71722961515a610e185a30689d5" +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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..c72fd566d5f16aea59cc24be96eee21c30c8b936 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_scope_vars.py::test_max_skip" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__0xzrqz4z/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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..19ad58db8e1a471e5f7172a30c9033e5b21541d9 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "b014f638cc6fc03a9149bc568f327f2d8eb6c614972f7ba640be8c21e4c87918", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "8a120539983d1ffb653310e479eef62cebd6ccf79f882011af4340ecf83450bb", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "d14de7c804cbfca664448ae9f9e7102da9c0817b", + "source_completion_sha256": "3f6ff664570f999d60c0e018cbfa1db3a0508c185027df0be5e86de1879347a7", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "16c4015a5ad481d4b9fcdff32356325ff53ead5ce3a080bcebffb0cbbfde096a", + "is_fork": true, + "learner_path": "tasks/d8422e33bf874c872c9cf270/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/d14de7c804cbfca664448ae9f9e7102da9c0817b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3083bb9c7dd6dd49e60d0043d3e91560ccd975e3a0f2ca20a3c3f2561b7b3404", + "provenance_path": "tasks/d8422e33bf874c872c9cf270/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d14de7c804cbfca664448ae9f9e7102da9c0817b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5a05f56acef3a5625b538ef9ec0f8d81ad8b3ebe", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "task_sha256": "93bfd6112311bf3ba8be2afb2656b7c412b64567f1dd8d2107f4a7bcf8bcfcb0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..81415fe1bf25e960158c655552ac1ecdcad46c57 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/instruction.md @@ -0,0 +1,29 @@ +Path repr shows incorrect slice when path has multiple elements + +#### Description + +When creating a Path object with multiple elements, the `__repr__` method displays an incorrect slice of the path operations. The representation is missing the last element of the path. + +#### Steps/Code to Reproduce + +```python +from glom import Path, T + +# Create a path with multiple elements +path = Path('a', 'b', 'c') +print(repr(path)) +# Expected: Path('a', 'b', 'c') +# Actual: Path('a', 'b') + +# Another example with T operations +path2 = Path('a', T.copy(), 'd') +print(repr(path2)) +# Expected: Path('a', T.copy(), 'd') +# Actual: Path('a', T.copy()) +``` + +The issue affects any Path with more than one element - the last element is consistently omitted from the string representation, making debugging and error messages confusing since they don't show the complete path. + +## 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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..849478d5617ead36e3234c32c054a6746ab3915a --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "5a05f56acef3a5625b538ef9ec0f8d81ad8b3ebe", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "d14de7c804cbfca664448ae9f9e7102da9c0817b" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_error.py", + "glom/test/test_mutation.py", + "glom/test/test_path_and_t.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": [ + "glom/core.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1390904, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "16c4015a5ad481d4b9fcdff32356325ff53ead5ce3a080bcebffb0cbbfde096a", + "is_fork": true, + "learner_path": "tasks/d8422e33bf874c872c9cf270/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/d14de7c804cbfca664448ae9f9e7102da9c0817b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3083bb9c7dd6dd49e60d0043d3e91560ccd975e3a0f2ca20a3c3f2561b7b3404", + "provenance_path": "tasks/d8422e33bf874c872c9cf270/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d14de7c804cbfca664448ae9f9e7102da9c0817b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5a05f56acef3a5625b538ef9ec0f8d81ad8b3ebe", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "task_sha256": "93bfd6112311bf3ba8be2afb2656b7c412b64567f1dd8d2107f4a7bcf8bcfcb0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f65b9fa88c176d9fc96455aef1cd0496b766a00d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "b014f638cc6fc03a9149bc568f327f2d8eb6c614972f7ba640be8c21e4c87918", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/d14de7c804cbfca664448ae9f9e7102da9c0817b/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "3f6ff664570f999d60c0e018cbfa1db3a0508c185027df0be5e86de1879347a7", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "6a7895063d9c285e9175c1bdf9229082eaea88979f14a715fad14855cc13e561", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "16c4015a5ad481d4b9fcdff32356325ff53ead5ce3a080bcebffb0cbbfde096a", + "is_fork": true, + "learner_path": "tasks/d8422e33bf874c872c9cf270/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/d14de7c804cbfca664448ae9f9e7102da9c0817b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "3083bb9c7dd6dd49e60d0043d3e91560ccd975e3a0f2ca20a3c3f2561b7b3404", + "provenance_path": "tasks/d8422e33bf874c872c9cf270/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d14de7c804cbfca664448ae9f9e7102da9c0817b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "5a05f56acef3a5625b538ef9ec0f8d81ad8b3ebe", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__1xv71j19", + "task_sha256": "93bfd6112311bf3ba8be2afb2656b7c412b64567f1dd8d2107f4a7bcf8bcfcb0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..78127fbac7c31d381bd2d25b9c0faa720ec3f24e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/glom/core.py b/glom/core.py +index bab56a024b16f0344eb08ecec0b8645a1f071c7a..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -751,7 +751,7 @@ + return Path(new_t) + + def __repr__(self): +- return _format_path(self.path_t.__ops__[:-1]) ++ return _format_path(self.path_t.__ops__[1:]) + + + def _format_path(t_path): diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..37589d4995244427894348fe7843331c73347048 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/core.py b/glom/core.py +index bab56a024b16f0344eb08ecec0b8645a1f071c7a..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -751,7 +751,7 @@ + return Path(new_t) + + def __repr__(self): +- return _format_path(self.path_t.__ops__[:-1]) ++ return _format_path(self.path_t.__ops__[1:]) + + + def _format_path(t_path): +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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3963f5d0caf01ff1243c89a20b0c8c65aba4ab45 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:a66724da0544ebb218dbb8db660a9186726ddde03733d4ccfa80bf7311e3bdf1" +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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..1233febf6343b026f39aa933a413101169910b02 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__1xv71j19/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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..c09e2ef81ca0e0d3b30e96364d7796aa7149c57f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "5a1d81f50325e91517e75bdbd0710b5cc49ac70f0162c0ebb3c3cf334ae5d272", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "865b02cf01a3c483256f7d4666594a974d3039f8b510047351ab3a6b5d819242", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "ffe8c4bcde43cbf3ce352a124c3670ea93477403", + "source_completion_sha256": "e996dfb1145d760850731e765b751670ad28d4251fb815d3e2c6ae144ef10e36", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "f113b19af0cfde8860230c2d6ffca9657378e7994e501987a903a26f679017fe", + "is_fork": true, + "learner_path": "tasks/c416bc451a7aa323027a8771/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/ffe8c4bcde43cbf3ce352a124c3670ea93477403/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "c096c6cbaf87dfbf74b4ede4cda11f09de832322ef1587c0758a91628ae1edcc", + "provenance_path": "tasks/c416bc451a7aa323027a8771/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ffe8c4bcde43cbf3ce352a124c3670ea93477403", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "c82d11cde244c310dfdc81a9a4cf309b7b5ab002", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "task_sha256": "e602f7def45710fa53ffa42858a36b07fa813a906ad4e575f94f31e7ef5d3564", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..651ef49bb64ea84e8188903e494524fde7cd9af2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/instruction.md @@ -0,0 +1,29 @@ +Match expression repr formatting broken + +When using match expressions with operators, the repr output is incorrectly formatted. The operator and operands are swapped in the string representation. + +#### Steps/Code to Reproduce + +```python +from glom.matching import M, And + +# Create a match expression +expr = And(M == 1, float) +print(repr(expr)) +``` + +Expected output: +``` +(M == 1) & float +``` + +Actual output: +``` +(M 1 '==') & float +``` + +The issue appears to affect the string representation of match expressions where the operator position and operand formatting is incorrect in the `__repr__` method. + +## 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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..330b022850b2e286f10173a053855dff5c7a2ec3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_match.py::test_reprs" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "c82d11cde244c310dfdc81a9a4cf309b7b5ab002", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "ffe8c4bcde43cbf3ce352a124c3670ea93477403" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_match.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": [ + "glom/matching.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1412694, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "f113b19af0cfde8860230c2d6ffca9657378e7994e501987a903a26f679017fe", + "is_fork": true, + "learner_path": "tasks/c416bc451a7aa323027a8771/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/ffe8c4bcde43cbf3ce352a124c3670ea93477403/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "c096c6cbaf87dfbf74b4ede4cda11f09de832322ef1587c0758a91628ae1edcc", + "provenance_path": "tasks/c416bc451a7aa323027a8771/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ffe8c4bcde43cbf3ce352a124c3670ea93477403", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "c82d11cde244c310dfdc81a9a4cf309b7b5ab002", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "task_sha256": "e602f7def45710fa53ffa42858a36b07fa813a906ad4e575f94f31e7ef5d3564", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..1175ff826766fc63727be72db2c5386e83ee34ad --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "5a1d81f50325e91517e75bdbd0710b5cc49ac70f0162c0ebb3c3cf334ae5d272", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/ffe8c4bcde43cbf3ce352a124c3670ea93477403/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "e996dfb1145d760850731e765b751670ad28d4251fb815d3e2c6ae144ef10e36", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "9bbcaf224f5b35f4fb08ad8845388ce91537f8d682f99e83de815338afe392c1", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "f113b19af0cfde8860230c2d6ffca9657378e7994e501987a903a26f679017fe", + "is_fork": true, + "learner_path": "tasks/c416bc451a7aa323027a8771/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/ffe8c4bcde43cbf3ce352a124c3670ea93477403/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "c096c6cbaf87dfbf74b4ede4cda11f09de832322ef1587c0758a91628ae1edcc", + "provenance_path": "tasks/c416bc451a7aa323027a8771/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ffe8c4bcde43cbf3ce352a124c3670ea93477403", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "c82d11cde244c310dfdc81a9a4cf309b7b5ab002", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2doj07s1", + "task_sha256": "e602f7def45710fa53ffa42858a36b07fa813a906ad4e575f94f31e7ef5d3564", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..d5fc5fec8a6cc4a8e2746073771529f4ff5c7ccb --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/provided-gold.diff @@ -0,0 +1,15 @@ +diff --git a/glom/matching.py b/glom/matching.py +index 69e5b941039247baf2e569eea5c93b5005135066..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -461,8 +461,8 @@ + raise MatchError("{0!r} {1} {2!r}", lhs, _M_OP_MAP.get(op, op), rhs) + + def __repr__(self): +- op = _M_OP_MAP.get(self.op, self.rhs) +- return f"{self.lhs!r} {self.rhs} {op!r}" ++ op = _M_OP_MAP.get(self.op, self.op) ++ return f"{self.lhs!r} {op} {self.rhs!r}" + + + class _MType: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba78067c49d398bab69268f2c325903bdb142cfd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/solution/solve.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/matching.py b/glom/matching.py +index 69e5b941039247baf2e569eea5c93b5005135066..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -461,8 +461,8 @@ + raise MatchError("{0!r} {1} {2!r}", lhs, _M_OP_MAP.get(op, op), rhs) + + def __repr__(self): +- op = _M_OP_MAP.get(self.op, self.rhs) +- return f"{self.lhs!r} {self.rhs} {op!r}" ++ op = _M_OP_MAP.get(self.op, self.op) ++ return f"{self.lhs!r} {op} {self.rhs!r}" + + + class _MType: +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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee2f9269589666ebb3c85de96b052af002086826 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:5ad45106fa08f48ef0625346eb82c5023f9817857881158f7814df76e505965b" +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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..4e52499ebab028fbde64c9a83e98935e563bcfbd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_match.py::test_reprs" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2doj07s1/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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..9d6208b6eda3c9776175c3233aee74ad6e19f83a --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "dd89f0fa07b50f77fc0a829848450f52ec2e07b7074e015d92f73e8a7991f621", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "011096a41a3586c82821997007c69d2ca8814bf5b81f65f2c7221eca5c4c2547", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "42e354c66167590dad8514b94adc45ab37a7c18b", + "source_completion_sha256": "af3f9bd30d6dbda6c7f80f2277827437449773685d05d77056c25cdf1db55455", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "edd9ce5aa25fbfa0373c257967d290bce7ffc6369ee4cdc016cb17f4d1ef49fc", + "is_fork": true, + "learner_path": "tasks/297367727404e07559843e5b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/42e354c66167590dad8514b94adc45ab37a7c18b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "09208e9d9995011f7cfb822a38ea7cc0e1c870482d413b7d59ca1e3797e1375a", + "provenance_path": "tasks/297367727404e07559843e5b/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "42e354c66167590dad8514b94adc45ab37a7c18b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "14d22f9298b1813458fd084d68a43314e3186610", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "task_sha256": "04f2c13774c05cbd6b3d6db340b12ed13eeb5fd8a6b61a1013eab0e10ee6cec1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f4b6ee0552738e880aba68fd3f3af3985a3d2f5e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/instruction.md @@ -0,0 +1,27 @@ +TType division operator returns operands in wrong order + +#### Description + +The `__truediv__` method in the `TType` class has its operands reversed, causing division operations to produce incorrect results. + +#### Steps/Code to Reproduce + +```python +from glom import glom, T + +# Simple division test +t = 2 +result = glom(t, T / 1) +print(f"Expected: 2.0, Got: {result}") + +# More complex example showing the issue +data = [0, 1, 2, 3, 4, 5] +result = glom(data, [T / 10.0]) +print(f"Expected: [0.0, 0.1, 0.2, 0.3, 0.4, 0.5], Got: {result}") +``` + +The division `T / 1` should return `2 / 1 = 2`, but instead returns `1 / 2 = 0.5`. Similarly, `T / 10.0` for each element should divide the element by 10, but instead divides 10 by the element. + +## 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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..cc68d70d8c4390753d793f0334cc2d0d2648b7cc --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "14d22f9298b1813458fd084d68a43314e3186610", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "42e354c66167590dad8514b94adc45ab37a7c18b" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_grouping.py", + "glom/test/test_path_and_t.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": [ + "glom/core.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1414733, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "edd9ce5aa25fbfa0373c257967d290bce7ffc6369ee4cdc016cb17f4d1ef49fc", + "is_fork": true, + "learner_path": "tasks/297367727404e07559843e5b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/42e354c66167590dad8514b94adc45ab37a7c18b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "09208e9d9995011f7cfb822a38ea7cc0e1c870482d413b7d59ca1e3797e1375a", + "provenance_path": "tasks/297367727404e07559843e5b/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "42e354c66167590dad8514b94adc45ab37a7c18b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "14d22f9298b1813458fd084d68a43314e3186610", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "task_sha256": "04f2c13774c05cbd6b3d6db340b12ed13eeb5fd8a6b61a1013eab0e10ee6cec1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..30b640494e5672eff9df8a77585ab3a26026222a --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "dd89f0fa07b50f77fc0a829848450f52ec2e07b7074e015d92f73e8a7991f621", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/42e354c66167590dad8514b94adc45ab37a7c18b/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "af3f9bd30d6dbda6c7f80f2277827437449773685d05d77056c25cdf1db55455", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "88100c39f08719a408b3d3a872f0e5341462aaa4943cb6b2bef3f3f3de9454e1", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "edd9ce5aa25fbfa0373c257967d290bce7ffc6369ee4cdc016cb17f4d1ef49fc", + "is_fork": true, + "learner_path": "tasks/297367727404e07559843e5b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/42e354c66167590dad8514b94adc45ab37a7c18b/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "09208e9d9995011f7cfb822a38ea7cc0e1c870482d413b7d59ca1e3797e1375a", + "provenance_path": "tasks/297367727404e07559843e5b/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "42e354c66167590dad8514b94adc45ab37a7c18b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "14d22f9298b1813458fd084d68a43314e3186610", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2dx4odj4", + "task_sha256": "04f2c13774c05cbd6b3d6db340b12ed13eeb5fd8a6b61a1013eab0e10ee6cec1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..dfed72b4a11d0cc0514019b30b1eab05a8b9d176 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/glom/core.py b/glom/core.py +index e6b3622a2182d72f26856ac543911de7ced9e738..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -1469,7 +1469,7 @@ + return _t_child(self, '#', arg) + + def __truediv__(self, arg): +- return _t_child(arg, '/', self) ++ return _t_child(self, '/', arg) + + __div__ = __truediv__ + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0add305724742baa28acf33579c2ce24c9840e23 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/core.py b/glom/core.py +index e6b3622a2182d72f26856ac543911de7ced9e738..cee71a307975ac747367aa346208aac00f07c223 100644 +--- a/glom/core.py ++++ b/glom/core.py +@@ -1469,7 +1469,7 @@ + return _t_child(self, '#', arg) + + def __truediv__(self, arg): +- return _t_child(arg, '/', self) ++ return _t_child(self, '/', arg) + + __div__ = __truediv__ + +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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7f3c3cbb8c75da905d35d17a9f643f942463b048 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:44f94efb50005519abec04a2c862669416ec8058116c98cff6c77ff406fb924d" +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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..1ed2355885732f560a3b2067138d75ae9d8fb010 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2dx4odj4/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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..4dd924b104ff9be6f9ccb5b2282a51bbed7b80b3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "7bd28094a72887b98b374991851460ae0787db92741fb869fd0fb2ce74418774", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "89d82b0ee8c4f9d688048f6354ee740ee7c353cd35924ae7e8c4497fedc87755", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "10b6fbf546c9fedcf72b54f1181ad3c29bc2be41", + "source_completion_sha256": "5db24fb8321be435962eb7d097edb1b0979ba5eb4a6367b8b58d6d887bacd9ab", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "c89cd2ec5cde639b5fa186d7d586fb5d69c238f26752c9b72bf4249de9c94ebe", + "is_fork": true, + "learner_path": "tasks/cbf416dfa728070bb71bc423/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/10b6fbf546c9fedcf72b54f1181ad3c29bc2be41/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "95242ea6f62e808c7b1f32b818f7641a35b2ed6236e99d0c02252fb192b14092", + "provenance_path": "tasks/cbf416dfa728070bb71bc423/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "10b6fbf546c9fedcf72b54f1181ad3c29bc2be41", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f68305a0d510f4d7d517604291901791dea731bf", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "task_sha256": "974d85beb131b063b167ec21d945fe27ef3aa209f999c5f66dd3c415482c25b4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..172bc8dfe97d99db6e509dd04a6d8e3999bce017 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/instruction.md @@ -0,0 +1,27 @@ +CLI main function returns incorrect exit codes + +#### Description + +The CLI main function is not returning proper exit codes when commands succeed. Instead of returning 0 for successful operations, it's returning unexpected values. + +#### Steps/Code to Reproduce + +```python +from glom import cli + +# This should return 0 for success but doesn't +argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] +result = cli.main(argv) +print(f"Expected: 0, Got: {result}") + +# These should also return 0 for success +argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] +result = cli.main(argv) +print(f"Expected: 0, Got: {result}") +``` + +The main function should return 0 when commands execute successfully, but it's returning other values instead. + +## 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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..c4602454c276fa2ec6caf12788b6b7fbacb43167 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "f68305a0d510f4d7d517604291901791dea731bf", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "10b6fbf546c9fedcf72b54f1181ad3c29bc2be41" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_error.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_match.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_cli.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": [ + "glom/cli.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1421926, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "c89cd2ec5cde639b5fa186d7d586fb5d69c238f26752c9b72bf4249de9c94ebe", + "is_fork": true, + "learner_path": "tasks/cbf416dfa728070bb71bc423/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/10b6fbf546c9fedcf72b54f1181ad3c29bc2be41/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "95242ea6f62e808c7b1f32b818f7641a35b2ed6236e99d0c02252fb192b14092", + "provenance_path": "tasks/cbf416dfa728070bb71bc423/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "10b6fbf546c9fedcf72b54f1181ad3c29bc2be41", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f68305a0d510f4d7d517604291901791dea731bf", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "task_sha256": "974d85beb131b063b167ec21d945fe27ef3aa209f999c5f66dd3c415482c25b4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..89ab2ff56add33693f99986c9deb8ca9207ce5ff --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "7bd28094a72887b98b374991851460ae0787db92741fb869fd0fb2ce74418774", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/10b6fbf546c9fedcf72b54f1181ad3c29bc2be41/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "5db24fb8321be435962eb7d097edb1b0979ba5eb4a6367b8b58d6d887bacd9ab", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "d1e11dd3c0061d986ca8ebdfb48b0452e0feabc3268580b02e3ff4b5e6e335fc", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "c89cd2ec5cde639b5fa186d7d586fb5d69c238f26752c9b72bf4249de9c94ebe", + "is_fork": true, + "learner_path": "tasks/cbf416dfa728070bb71bc423/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/10b6fbf546c9fedcf72b54f1181ad3c29bc2be41/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "95242ea6f62e808c7b1f32b818f7641a35b2ed6236e99d0c02252fb192b14092", + "provenance_path": "tasks/cbf416dfa728070bb71bc423/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "10b6fbf546c9fedcf72b54f1181ad3c29bc2be41", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f68305a0d510f4d7d517604291901791dea731bf", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb", + "task_sha256": "974d85beb131b063b167ec21d945fe27ef3aa209f999c5f66dd3c415482c25b4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..66f60cee8630d5d14833504ca274d93f124cfc82 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/glom/cli.py b/glom/cli.py +index 45f870566ccc3d7929525e187b943158b70d4e4f..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -100,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b66e9b09a1dd74852af0e9660cea06f171b3d2bd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/cli.py b/glom/cli.py +index 45f870566ccc3d7929525e187b943158b70d4e4f..298706420dec85a83ec8073ceb299376199296b8 100644 +--- a/glom/cli.py ++++ b/glom/cli.py +@@ -100,7 +100,7 @@ + + def main(argv): + cmd = get_command() +- return len(argv) and cmd.run(argv) ++ return cmd.run(argv) or 0 + + + def console_main(): +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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7e42f4fecedc1df187b949540c2ed8ddf066def5 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:0ef97a0823d9c22dee12f897c55400beb10eb57be4a568c6abf9b0f8fc3f59db" +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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..453e3b1c1e9197d1b5042593efc2ee7c42d1884e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2ldo3zqb/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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..7a57355b944516c7c6389c8330eca1df9ec11524 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "bbc42a16360aa05dd42eead42faf0cc5aa9475048856421705cb7801b50e6c20", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "0fba3a88eb97c259d7315ea610020d3ad121774d4ae587a73920e602e1ce6a89", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "3a3f1dae2980f9c154b2abf5a0a96ddd4cfd2feafe3c92ddf9f87133629790db", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "95f4ad3765572ccec122596149c1bd9642a0c41e", + "source_completion_sha256": "5d391c1a3e6a5a89919d927a853afd2547a1f1c5e5322c196a29ef4f6e68edb1", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "63b85a4237f1bb753d020abfa1c05c4f4b886dfed523b19bae29a7be30b3a9d5", + "is_fork": true, + "learner_path": "tasks/0a7fe8290e94d348ec2dba88/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/95f4ad3765572ccec122596149c1bd9642a0c41e/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "8c2e5f180b98b088eb223db6fb826f46419549bb1c1ef60fba742afe00fd5ae2", + "provenance_path": "tasks/0a7fe8290e94d348ec2dba88/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "95f4ad3765572ccec122596149c1bd9642a0c41e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "903b6c28a09f55062cffc9e1efbf4e8a4a2cc8fb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "task_sha256": "9f4428b74e47d598983fe0a217ffbb6a4edf4718c63ed07b3754fdc4beee43dc", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83d25a8b6452e7262ce13ba0635ff18e159f77bd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/instruction.md @@ -0,0 +1,40 @@ +Match function broken after recent changes + +#### Description + +The `Match` function is not working correctly. Basic matching operations are failing with unexpected errors. + +#### Steps/Code to Reproduce + +```python +from glom import glom, Match + +# Simple integer matching fails +try: + result = glom(1, Match(1)) + print(f"Expected: 1, Got: {result}") +except Exception as e: + print(f"Error: {e}") + +# Type matching also broken +try: + result = glom(1, Match(int)) + print(f"Expected: 1, Got: {result}") +except Exception as e: + print(f"Error: {e}") + +# List matching fails too +try: + result = glom([1], Match([int])) + print(f"Expected: [1], Got: {result}") +except Exception as e: + print(f"Error: {e}") +``` + +Expected output should be the matched values, but instead getting various errors like `MatchError` and `UnboundLocalError`. + +The matching logic seems completely broken - even simple cases like matching a literal value `1` against `Match(1)` are failing. + +## 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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8ffe3cd83aba6ace52c80ed00c9d7cd0f4f52c0d --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "903b6c28a09f55062cffc9e1efbf4e8a4a2cc8fb", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "95f4ad3765572ccec122596149c1bd9642a0c41e" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_scope_vars.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_error.py", + "glom/test/test_match.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": [ + "glom/matching.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1395073, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "63b85a4237f1bb753d020abfa1c05c4f4b886dfed523b19bae29a7be30b3a9d5", + "is_fork": true, + "learner_path": "tasks/0a7fe8290e94d348ec2dba88/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/95f4ad3765572ccec122596149c1bd9642a0c41e/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "8c2e5f180b98b088eb223db6fb826f46419549bb1c1ef60fba742afe00fd5ae2", + "provenance_path": "tasks/0a7fe8290e94d348ec2dba88/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "95f4ad3765572ccec122596149c1bd9642a0c41e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "903b6c28a09f55062cffc9e1efbf4e8a4a2cc8fb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "task_sha256": "9f4428b74e47d598983fe0a217ffbb6a4edf4718c63ed07b3754fdc4beee43dc", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d615266c011b0a41c4ebc6d8e10bd36ad3783b71 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "bbc42a16360aa05dd42eead42faf0cc5aa9475048856421705cb7801b50e6c20", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/95f4ad3765572ccec122596149c1bd9642a0c41e/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "5d391c1a3e6a5a89919d927a853afd2547a1f1c5e5322c196a29ef4f6e68edb1", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "a1991f39cdce939146f8b404c110b8b134533d2b6cdee9c7f31e0b6a8dc2af55", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "63b85a4237f1bb753d020abfa1c05c4f4b886dfed523b19bae29a7be30b3a9d5", + "is_fork": true, + "learner_path": "tasks/0a7fe8290e94d348ec2dba88/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/95f4ad3765572ccec122596149c1bd9642a0c41e/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "8c2e5f180b98b088eb223db6fb826f46419549bb1c1ef60fba742afe00fd5ae2", + "provenance_path": "tasks/0a7fe8290e94d348ec2dba88/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "95f4ad3765572ccec122596149c1bd9642a0c41e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "903b6c28a09f55062cffc9e1efbf4e8a4a2cc8fb", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__2npzx06l", + "task_sha256": "9f4428b74e47d598983fe0a217ffbb6a4edf4718c63ed07b3754fdc4beee43dc", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..dfdd93b20fc3fe0cc3de6c4a4bfd0487d50dc579 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/provided-gold.diff @@ -0,0 +1,85 @@ +diff --git a/glom/matching.py b/glom/matching.py +index c469db3d37c77c86de9f3bc2d17f7583fb3035e1..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -712,13 +712,13 @@ + + + def _glom_match(target, spec, scope): +- if isinstance(spec, dict): +- return _handle_dict(target, spec, scope) +- elif isinstance(spec, type): ++ if isinstance(spec, type): + if not isinstance(target, spec): + raise TypeMatchError(type(target), spec) +- elif isinstance(spec, (set, list, frozenset)): +- if not isinstance(target, list if spec else type(spec)): ++ elif isinstance(spec, dict): ++ return _handle_dict(target, spec, scope) ++ elif isinstance(spec, (list, set, frozenset)): ++ if not isinstance(target, type(spec)): + raise TypeMatchError(type(target), type(spec)) + result = [] + for item in target: +@@ -726,38 +726,39 @@ + try: + result.append(scope[glom](item, child, scope)) + break +- except GlomError: +- last_error = MatchError("{0!r} does not match {1!r}", target, spec) +- else: +- if target or spec: +- raise last_error +- else: ++ except GlomError as e: ++ last_error = e ++ else: # did not break, something went wrong ++ if target and not spec: + raise MatchError( +- "{0!r} matches empty {1}", target, type(spec).__name__) +- if set(spec) == list: +- return result +- return type(spec)(result) ++ "{0!r} does not match empty {1}", target, type(spec).__name__) ++ # NOTE: unless error happens above, break will skip else branch ++ # so last_error will have been assigned ++ raise last_error ++ if type(spec) is not list: ++ return type(spec)(result) ++ return result + elif isinstance(spec, tuple): +- if not isinstance(target, spec): ++ if not isinstance(target, tuple): + raise TypeMatchError(type(target), tuple) +- if len(target) == len(spec): +- raise MatchError("{0!r} cannot match {1!r}", target, spec) ++ if len(target) != len(spec): ++ raise MatchError("{0!r} does not match {1!r}", target, spec) + result = [] +- for sub_target, sub_spec in zip(spec, target): ++ for sub_target, sub_spec in zip(target, spec): + result.append(scope[glom](sub_target, sub_spec, scope)) + return tuple(result) + elif callable(spec): + try: +- if target(target): +- return spec +- except Exception: ++ if spec(target): ++ return target ++ except Exception as e: + raise MatchError( +- "{0}({1!r}) validation exception", spec.__name__, target) ++ "{0}({1!r}) did not validate (got exception {2!r})", spec.__name__, target, e) + raise MatchError( +- "{0}({1!r}) resulted false", spec.__name__, target) +- elif target == spec: +- raise MatchError("{0!r} matches {1!r}", target, spec) +- return spec ++ "{0}({1!r}) did not validate (non truthy return)", spec.__name__, target) ++ elif target != spec: ++ raise MatchError("{0!r} does not match {1!r}", target, spec) ++ return target + + + class Switch: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a4746ad6b56e8d3829406b733db5a59b4bbf542 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/solution/solve.sh @@ -0,0 +1,91 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/matching.py b/glom/matching.py +index c469db3d37c77c86de9f3bc2d17f7583fb3035e1..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -712,13 +712,13 @@ + + + def _glom_match(target, spec, scope): +- if isinstance(spec, dict): +- return _handle_dict(target, spec, scope) +- elif isinstance(spec, type): ++ if isinstance(spec, type): + if not isinstance(target, spec): + raise TypeMatchError(type(target), spec) +- elif isinstance(spec, (set, list, frozenset)): +- if not isinstance(target, list if spec else type(spec)): ++ elif isinstance(spec, dict): ++ return _handle_dict(target, spec, scope) ++ elif isinstance(spec, (list, set, frozenset)): ++ if not isinstance(target, type(spec)): + raise TypeMatchError(type(target), type(spec)) + result = [] + for item in target: +@@ -726,38 +726,39 @@ + try: + result.append(scope[glom](item, child, scope)) + break +- except GlomError: +- last_error = MatchError("{0!r} does not match {1!r}", target, spec) +- else: +- if target or spec: +- raise last_error +- else: ++ except GlomError as e: ++ last_error = e ++ else: # did not break, something went wrong ++ if target and not spec: + raise MatchError( +- "{0!r} matches empty {1}", target, type(spec).__name__) +- if set(spec) == list: +- return result +- return type(spec)(result) ++ "{0!r} does not match empty {1}", target, type(spec).__name__) ++ # NOTE: unless error happens above, break will skip else branch ++ # so last_error will have been assigned ++ raise last_error ++ if type(spec) is not list: ++ return type(spec)(result) ++ return result + elif isinstance(spec, tuple): +- if not isinstance(target, spec): ++ if not isinstance(target, tuple): + raise TypeMatchError(type(target), tuple) +- if len(target) == len(spec): +- raise MatchError("{0!r} cannot match {1!r}", target, spec) ++ if len(target) != len(spec): ++ raise MatchError("{0!r} does not match {1!r}", target, spec) + result = [] +- for sub_target, sub_spec in zip(spec, target): ++ for sub_target, sub_spec in zip(target, spec): + result.append(scope[glom](sub_target, sub_spec, scope)) + return tuple(result) + elif callable(spec): + try: +- if target(target): +- return spec +- except Exception: ++ if spec(target): ++ return target ++ except Exception as e: + raise MatchError( +- "{0}({1!r}) validation exception", spec.__name__, target) ++ "{0}({1!r}) did not validate (got exception {2!r})", spec.__name__, target, e) + raise MatchError( +- "{0}({1!r}) resulted false", spec.__name__, target) +- elif target == spec: +- raise MatchError("{0!r} matches {1!r}", target, spec) +- return spec ++ "{0}({1!r}) did not validate (non truthy return)", spec.__name__, target) ++ elif target != spec: ++ raise MatchError("{0!r} does not match {1!r}", target, spec) ++ return target + + + class Switch: +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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a5d29ff8a214d29c26108415751e8067269d8f2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:9bdcca717fe9406020a4cdb6a997479a4defd764711c5fa13f5d7bf5e56f1536" +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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..59af5729505619793585fb4e703a06888e31d904 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_check_ported_tests" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_max_skip", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted-inventory.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1f31441c1c1d85c34182cf01815eae5a9b16ba --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted-inventory.json @@ -0,0 +1,132 @@ +{ + "directory_roots": [ + "glom/test" + ], + "files": { + "glom/test/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "glom/test/data/test_invalid.toml": { + "bytes": 19, + "mode": 420, + "sha256": "f59a1d038e1648113ad5f0452ea99b79fc29d1eac035959e95d1c27ff44dc144" + }, + "glom/test/data/test_invalid.yaml": { + "bytes": 15, + "mode": 420, + "sha256": "a5de9f6a4b0a10d16777fc47f58e96271303682d0c7fbd439a034d824e6f5b08" + }, + "glom/test/data/test_valid.toml": { + "bytes": 18, + "mode": 420, + "sha256": "a13bb47add7b013b3086e4530f1f8daf2149bc4c3ae97237ff84f95facf4f5c5" + }, + "glom/test/data/test_valid.yaml": { + "bytes": 23, + "mode": 420, + "sha256": "0d40245ac0403c81a09e8521140c9ef50da30d8031efc6aef25fcb44be24362a" + }, + "glom/test/perf_report.py": { + "bytes": 1962, + "mode": 420, + "sha256": "da3294405f48e1b4e46b133eb8abb514019b4cc46547bd12c7bea65ef56467ed" + }, + "glom/test/test_basic.py": { + "bytes": 14233, + "mode": 420, + "sha256": "364581bf0f191b243d73f0cf5558cc9152126fd83c7fca1d97f953bf5478fd85" + }, + "glom/test/test_check.py": { + "bytes": 3539, + "mode": 420, + "sha256": "0c1b41b64de13ee16b508439b1f5a8fe994e10d9ccc6d64ba6a81fea67ee5fe6" + }, + "glom/test/test_cli.py": { + "bytes": 6191, + "mode": 420, + "sha256": "457d77b17aadb5b1ed0aa44cec6a3936a8703b47ddb07d4c0e0949859bc442de" + }, + "glom/test/test_error.py": { + "bytes": 17299, + "mode": 420, + "sha256": "8342c238c3e24925f90e9cd5619353cadccff708b1abe5892582ec8ece168d21" + }, + "glom/test/test_fill.py": { + "bytes": 708, + "mode": 420, + "sha256": "bba9a52291035bec99fb89969f9b2a50641ded20efdcdb3252ebf547f08ae61f" + }, + "glom/test/test_grouping.py": { + "bytes": 3261, + "mode": 420, + "sha256": "5cfd0f1f8be4ab7e833463475f6a74ac20e486a769421f5d678612dfc79df15b" + }, + "glom/test/test_match.py": { + "bytes": 15407, + "mode": 420, + "sha256": "43848620cde516f267baff40fc8f7a32e7701a0cb56c9e020114c88d4805650b" + }, + "glom/test/test_mutation.py": { + "bytes": 9793, + "mode": 420, + "sha256": "01f869a7165704d71985cda35cff5f50b45c51874a747a414cd11bf45d2fd89a" + }, + "glom/test/test_path_and_t.py": { + "bytes": 10105, + "mode": 420, + "sha256": "0138a53ea1db7faa8db879f590675c02189e8dd7a976af3122f4e8d14f206720" + }, + "glom/test/test_reduction.py": { + "bytes": 4159, + "mode": 420, + "sha256": "374466255beea308e8b9429eb7fe4ec77046e1aa3234967c57d9be7f9fbf8064" + }, + "glom/test/test_scope_vars.py": { + "bytes": 3400, + "mode": 420, + "sha256": "71639cf6909c359a16399015a963b1ea21d1b166982836e0203417f1e9cd1c18" + }, + "glom/test/test_snippets.py": { + "bytes": 1478, + "mode": 420, + "sha256": "14f42ea07f26b7ba4edc8b9a1b4d85f4975a948fed7afea634bf25f73da2136c" + }, + "glom/test/test_spec.py": { + "bytes": 745, + "mode": 420, + "sha256": "ef3d891517b4ebe35d8cdaad8b6778775a5260cf40697defc2c50981ff6fbe84" + }, + "glom/test/test_streaming.py": { + "bytes": 5664, + "mode": 420, + "sha256": "79fb6c7dcce0f50855df62c115822bfffaf1271b6131fdcff7fdd623e4189617" + }, + "glom/test/test_target_types.py": { + "bytes": 7621, + "mode": 420, + "sha256": "6605a6370d3eab24f7b3fa810aa0525417d0396bcba3ff1d31aedc46b60b58da" + }, + "glom/test/test_tutorial.py": { + "bytes": 463, + "mode": 420, + "sha256": "0790d2b2dbbadcbc06fa6b9467808f70568743f9d257c0313b7e2e974707e53f" + }, + "pytest.ini": { + "bytes": 83, + "mode": 420, + "sha256": "a08166d39b849cfb09dbe12650ad9947271eaa18962b08d161abc5fbd37fcb26" + }, + "setup.py": { + "bytes": 2793, + "mode": 420, + "sha256": "bf3f70521bcc74c8c85c05e65e7655a34629b767a50984985d50320d8fa547f2" + }, + "tox.ini": { + "bytes": 977, + "mode": 420, + "sha256": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_tutorial.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/pytest.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..f6cd3a762549585594244e7a1cbf6d7490afc531 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +doctest_optionflags=NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/setup.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8542f1428c09b8e4f638669e7f97764c626a3741 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/setup.py @@ -0,0 +1,88 @@ +import importlib.util +import os + +from setuptools import setup + +__author__ = 'Mahmoud Hashemi and Kurt Rose' +__contact__ = 'mahmoud@hatnote.com' +__url__ = 'https://github.com/mahmoud/glom' + + +def import_path(module_name, path): + spec = importlib.util.spec_from_file_location(module_name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CUR_PATH = os.path.abspath(os.path.dirname(__file__)) +_version_mod_path = os.path.join(CUR_PATH, 'glom', '_version.py') +_version_mod = import_path('_version', _version_mod_path) +__version__ = _version_mod.__version__ + + +open_kwarg = {} + +with open('README.md', encoding='utf8') as read_me: + long_description = read_me.read() + +setup(name='glom', + version=__version__, + description="A declarative object transformer and formatter, for conglomerating nested data.", + long_description=long_description, + long_description_content_type='text/markdown', + author=__author__, + author_email=__contact__, + url=__url__, + project_urls={ + 'Documentation': 'https://glom.readthedocs.io/en/latest/', + }, + packages=['glom', 'glom.test'], + install_requires=['boltons>=19.3.0', 'attrs', 'face>=20.1.1'], + extras_require={ + 'toml': ['tomli; python_version<"3.11"'], + 'yaml': ['PyYAML'], + }, + entry_points={'console_scripts': ['glom = glom.cli:console_main']}, + include_package_data=True, + zip_safe=False, + platforms='any', + license_files=['LICENSE'], + classifiers=[ + 'Topic :: Utilities', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries', + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python :: 3.7', + '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', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + 'License :: OSI Approved :: BSD License', + ] + ) + +""" +A brief checklist for release: + +* tox +* git commit (if applicable) +* Bump glom/_version.py off of -dev +* git commit -a -m "bump version for vx.y.z release" +* write CHANGELOG +* bump docs/conf.py version +* git commit +* rm -rf dist/* +* python setup.py sdist bdist_wheel +* twine upload dist/* +* git tag -a vx.y.z -m "brief summary" +* bump glom/_version.py onto n+1 dev +* git commit +* git push + +NB: if dropping support for a python version, bump the pyupgrade argument in tox and run syntax-upgrade tox env. + +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/tox.ini b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6b2255666537ce37af154c74de58e690393b54b6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/tests/trusted/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = py37,py38,py39,py310,py311,py312,pypy3,coverage-report,packaging + +[testenv] +changedir = .tox +deps = -rrequirements.txt +commands = coverage run --parallel --rcfile {toxinidir}/.tox-coveragerc -m pytest -vv --doctest-modules {envsitepackagesdir}/glom {posargs} + +[testenv:coverage-report] +changedir = .tox +deps = coverage +commands = coverage combine --rcfile {toxinidir}/.tox-coveragerc + coverage xml --rcfile {toxinidir}/.tox-coveragerc + coverage report --rcfile {toxinidir}/.tox-coveragerc + coverage html --rcfile {toxinidir}/.tox-coveragerc -d {toxinidir}/htmlcov + + +[testenv:packaging] +changedir = {toxinidir} +deps = + check-manifest==0.50 +commands = + check-manifest + +[testenv:syntax-upgrade] +changedir = {toxinidir} +deps = + flynt + pyupgrade +commands = + flynt ./glom + python -c "import glob; import subprocess; [subprocess.run(['pyupgrade', '--py37-plus', f]) for f in glob.glob('./glom/**/*.py', recursive=True)]" \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/canaries/first-hunk-only.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..76b51900fc798fb679dda2e12e9c532aa2a2649f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/canaries/first-hunk-only.sh @@ -0,0 +1,29 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/glom/matching.py b/glom/matching.py +index c469db3d37c77c86de9f3bc2d17f7583fb3035e1..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -712,13 +712,13 @@ + + + def _glom_match(target, spec, scope): +- if isinstance(spec, dict): +- return _handle_dict(target, spec, scope) +- elif isinstance(spec, type): ++ if isinstance(spec, type): + if not isinstance(target, spec): + raise TypeMatchError(type(target), spec) +- elif isinstance(spec, (set, list, frozenset)): +- if not isinstance(target, list if spec else type(spec)): ++ elif isinstance(spec, dict): ++ return _handle_dict(target, spec, scope) ++ elif isinstance(spec, (list, set, frozenset)): ++ if not isinstance(target, type(spec)): + raise TypeMatchError(type(target), type(spec)) + result = [] + for item in target: +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/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/canaries/original-bug.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/openenv.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__2npzx06l/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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/LICENSE.source b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..fc38888bcf934b1de7b64ab0b3ad7003d7a22fa1 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/LICENSE.source @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2018, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/adapter.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..6865110dccb86edb9fc607071798a75f4964b033 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/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": "9ddda27f6e3f1110fe05ebb169af5f430f596cda7379dc183f692dd46ea16655", + "gold_patch_sha256": "5d3c2eabcb8fe2672cd2d92a8dc511b2ab7bf128b1ab076a3e1fe8221f089c1b", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "b359f05a3414e54dc1fc7e349d30648d4db5b40d2c99a368fae9065e793f6ef3", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/mahmoud__glom.fb3c4e76.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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "51a805747c636aebe3d8e72b6d79cf5ce7bd71a5", + "source_completion_sha256": "175e2a6baa791316c58f5d45d3eaf2a3f05fd216ea3d23bb9d649984f65dfea8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "de9d26f18405ab4a4b11f7cf242c7c6eee3f33e77effa9b5a8729170b245a16c", + "is_fork": true, + "learner_path": "tasks/7dccca74fc1a257cb1b11c55/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/51a805747c636aebe3d8e72b6d79cf5ce7bd71a5/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "eea176c188b39563c641f41501e4e3ee7431c76db0137cd8928146a7e4ff5725", + "provenance_path": "tasks/7dccca74fc1a257cb1b11c55/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "51a805747c636aebe3d8e72b6d79cf5ce7bd71a5", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "91c4f15ceb580eeacdb6a9a521c6a1aca9d17505", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "task_sha256": "4cd921b17ee7e20a8d2e82690f3b551a9890da5483ee1203460a577a2617a023", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "symlink_submodule_changes_supported": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "mahmoud/glom" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/dependency-setup.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..07918e37bcec77c5e0b7a29cbcad8f6e0fa283f6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/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.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/environment/Dockerfile b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/instruction.md b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..107b5deab9baa64919ae37a53d6e6d5b328444f3 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/instruction.md @@ -0,0 +1,42 @@ +Match expressions return wrong values and have inverted logic + +#### Description + +Match expressions using the `M` object are behaving incorrectly. The comparison operators are inverted and the expressions return the wrong values when they should match. + +#### Steps/Code to Reproduce + +```python +from glom import glom, M + +# Basic equality check - should return 1 but fails +result = glom(1, M == 1) +print(f"Expected: 1, Got: {result}") + +# Greater than comparison - should return 2 but fails +result = glom(2, M > 1) +print(f"Expected: 2, Got: {result}") + +# Less than comparison - should return 0 but fails +result = glom(0, M < 1) +print(f"Expected: 0, Got: {result}") + +# These should all work but currently raise MatchError +try: + glom(1, M >= 1) + print("M >= 1 worked") +except Exception as e: + print(f"M >= 1 failed: {e}") + +try: + glom(1, M <= 1) + print("M <= 1 worked") +except Exception as e: + print(f"M <= 1 failed: {e}") +``` + +The match expressions seem to have their logic completely inverted - equality checks fail when they should pass, and comparisons 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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/metadata.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..21257707676d6ef27f626084ea0b3814e9521463 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/metadata.json @@ -0,0 +1,368 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_scope_vars.py::test_max_skip" + ], + "PASS_TO_PASS": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "91c4f15ceb580eeacdb6a9a521c6a1aca9d17505", + "healthy": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "learner": "51a805747c636aebe3d8e72b6d79cf5ce7bd71a5" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/.tox-coveragerc", + "/testbed/CHANGELOG.md", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/docs/Makefile", + "/testbed/docs/_static/comet.png", + "/testbed/docs/_static/comet_multi.png", + "/testbed/docs/_templates/page.html", + "/testbed/docs/api.rst", + "/testbed/docs/by_analogy.rst", + "/testbed/docs/cli.rst", + "/testbed/docs/conf.py", + "/testbed/docs/custom_spec_types.rst", + "/testbed/docs/debugging.rst", + "/testbed/docs/faq.rst", + "/testbed/docs/grouping.rst", + "/testbed/docs/index.rst", + "/testbed/docs/make.bat", + "/testbed/docs/matching.rst", + "/testbed/docs/modes.rst", + "/testbed/docs/mutation.rst", + "/testbed/docs/outreach.md", + "/testbed/docs/requirements-rtd.txt", + "/testbed/docs/snippets.rst", + "/testbed/docs/streaming.rst", + "/testbed/docs/tutorial.rst", + "/testbed/glom/__init__.py", + "/testbed/glom/__main__.py", + "/testbed/glom/_version.py", + "/testbed/glom/cli.py", + "/testbed/glom/core.py", + "/testbed/glom/grouping.py", + "/testbed/glom/matching.py", + "/testbed/glom/mutation.py", + "/testbed/glom/reduction.py", + "/testbed/glom/streaming.py", + "/testbed/glom/test/__init__.py", + "/testbed/glom/test/data/test_invalid.toml", + "/testbed/glom/test/data/test_invalid.yaml", + "/testbed/glom/test/data/test_valid.toml", + "/testbed/glom/test/data/test_valid.yaml", + "/testbed/glom/test/perf_report.py", + "/testbed/glom/test/test_basic.py", + "/testbed/glom/test/test_check.py", + "/testbed/glom/test/test_cli.py", + "/testbed/glom/test/test_fill.py", + "/testbed/glom/test/test_grouping.py", + "/testbed/glom/test/test_mutation.py", + "/testbed/glom/test/test_path_and_t.py", + "/testbed/glom/test/test_reduction.py", + "/testbed/glom/test/test_snippets.py", + "/testbed/glom/test/test_spec.py", + "/testbed/glom/test/test_streaming.py", + "/testbed/glom/test/test_target_types.py", + "/testbed/glom/test/test_tutorial.py", + "/testbed/glom/tutorial.py", + "/testbed/pytest.ini", + "/testbed/requirements.in", + "/testbed/requirements.txt", + "/testbed/setup.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": "GlomFb3c4e76", + "profile_lines": [ + 411, + 414 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "upstream_repo": "mahmoud/glom" + }, + "original_source_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "private_test_paths": [ + "glom/test/test_error.py", + "glom/test/test_match.py", + "glom/test/test_scope_vars.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": [ + "glom/matching.py" + ], + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_stages_bytes": 1392773, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "mahmoud/glom" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "de9d26f18405ab4a4b11f7cf242c7c6eee3f33e77effa9b5a8729170b245a16c", + "is_fork": true, + "learner_path": "tasks/7dccca74fc1a257cb1b11c55/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/51a805747c636aebe3d8e72b6d79cf5ce7bd71a5/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "eea176c188b39563c641f41501e4e3ee7431c76db0137cd8928146a7e4ff5725", + "provenance_path": "tasks/7dccca74fc1a257cb1b11c55/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "51a805747c636aebe3d8e72b6d79cf5ce7bd71a5", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "91c4f15ceb580eeacdb6a9a521c6a1aca9d17505", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "task_sha256": "4cd921b17ee7e20a8d2e82690f3b551a9890da5483ee1203460a577a2617a023", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/provenance.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ac97093a86492b67b5790af7fe963f8c79a94c42 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "5d3c2eabcb8fe2672cd2d92a8dc511b2ab7bf128b1ab076a3e1fe8221f089c1b", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/51a805747c636aebe3d8e72b6d79cf5ce7bd71a5/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "175e2a6baa791316c58f5d45d3eaf2a3f05fd216ea3d23bb9d649984f65dfea8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "447f3f16b5fac6cd873ff7c4ee197017a49a49711ef6a576361c4a74d5b08fcf", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "cefbc05bb4890356f3782b5ae0b33aef27a47536", + "instruction_sha256": "de9d26f18405ab4a4b11f7cf242c7c6eee3f33e77effa9b5a8729170b245a16c", + "is_fork": true, + "learner_path": "tasks/7dccca74fc1a257cb1b11c55/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "actual_upstream_url": "https://raw.githubusercontent.com/mahmoud/glom/fb3c4e76f28816aebfd2538980e617742e98a7c2/LICENSE", + "reviewed": true, + "sha256": "ba81ea9a55099a9c4491141f9aace8ffd1f169701815582d7a80ed57f7b625d5", + "spdx": "BSD-2-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/mahmoud__glom.fb3c4e76/51a805747c636aebe3d8e72b6d79cf5ce7bd71a5/LICENSE" + }, + "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": "fb3c4e76f28816aebfd2538980e617742e98a7c2", + "patch_sha256": "eea176c188b39563c641f41501e4e3ee7431c76db0137cd8928146a7e4ff5725", + "provenance_path": "tasks/7dccca74fc1a257cb1b11c55/source-proof.json", + "repository_lineage": [ + "swesmith/mahmoud__glom.fb3c4e76", + "mahmoud/glom" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "51a805747c636aebe3d8e72b6d79cf5ce7bd71a5", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "91c4f15ceb580eeacdb6a9a521c6a1aca9d17505", + "source_kind": "mutation", + "source_repo": "swesmith/mahmoud__glom.fb3c4e76", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "mahmoud__glom.fb3c4e76.func_basic__39aaz49a", + "task_sha256": "4cd921b17ee7e20a8d2e82690f3b551a9890da5483ee1203460a577a2617a023", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "mahmoud/glom", + "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": "f127918c1d9f14c9e2ca870c81e9f78fc07ca3c66c4f33dadc51eca2753c81f4" +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/provided-gold.diff b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..02a2206212c60e34044f894dba88247d5184f2a8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/provided-gold.diff @@ -0,0 +1,44 @@ +diff --git a/glom/matching.py b/glom/matching.py +index deb88fbe49d06355cbaa3fee7e247cd6a999e918..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -439,26 +439,26 @@ + return Not(self) + + def glomit(self, target, scope): +- lhs, op, rhs = self.rhs, self.op, self.lhs # Swapped lhs and rhs at assignment ++ lhs, op, rhs = self.lhs, self.op, self.rhs + if lhs is M: +- lhs = scope # Changed target to scope ++ lhs = target + if rhs is M: +- rhs = scope # Changed target to scope ++ rhs = target + if type(lhs) is _MSubspec: +- lhs = scope[glom](scope, lhs.spec, target) # Swapped scope and target arguments ++ lhs = scope[glom](target, lhs.spec, scope) + if type(rhs) is _MSubspec: +- rhs = scope[glom](scope, rhs.spec, target) # Swapped scope and target arguments ++ rhs = scope[glom](target, rhs.spec, scope) + matched = ( +- (op == '=' and lhs != rhs) or # Changed '==' to '!=' +- (op == '!' and lhs == rhs) or # Changed '!=' to '==' +- (op == '>' and lhs < rhs) or # Changed '>' to '<' +- (op == '<' and lhs > rhs) or # Changed '<' to '>' +- (op == 'g' and lhs <= rhs) or # Changed '>=' to '<=' +- (op == 'l' and lhs >= rhs) # Changed '<=' to '>=' ++ (op == '=' and lhs == rhs) or ++ (op == '!' and lhs != rhs) or ++ (op == '>' and lhs > rhs) or ++ (op == '<' and lhs < rhs) or ++ (op == 'g' and lhs >= rhs) or ++ (op == 'l' and lhs <= rhs) + ) + if matched: +- return scope # Changed return value from target to scope +- raise MatchError("{0!r} {1} {2!r}", rhs, _M_OP_MAP.get(op, op), lhs) # Swapped lhs and rhs in exception ++ return target ++ raise MatchError("{0!r} {1} {2!r}", lhs, _M_OP_MAP.get(op, op), rhs) + + def __repr__(self): + op = _M_OP_MAP.get(self.op, self.op) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/solution/solve.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..10eb0bea28fe1f0a0334ef083f4147c799b72132 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/solution/solve.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/glom/matching.py b/glom/matching.py +index deb88fbe49d06355cbaa3fee7e247cd6a999e918..798ac402c07ccc59280e61e002a4f28069e0748a 100644 +--- a/glom/matching.py ++++ b/glom/matching.py +@@ -439,26 +439,26 @@ + return Not(self) + + def glomit(self, target, scope): +- lhs, op, rhs = self.rhs, self.op, self.lhs # Swapped lhs and rhs at assignment ++ lhs, op, rhs = self.lhs, self.op, self.rhs + if lhs is M: +- lhs = scope # Changed target to scope ++ lhs = target + if rhs is M: +- rhs = scope # Changed target to scope ++ rhs = target + if type(lhs) is _MSubspec: +- lhs = scope[glom](scope, lhs.spec, target) # Swapped scope and target arguments ++ lhs = scope[glom](target, lhs.spec, scope) + if type(rhs) is _MSubspec: +- rhs = scope[glom](scope, rhs.spec, target) # Swapped scope and target arguments ++ rhs = scope[glom](target, rhs.spec, scope) + matched = ( +- (op == '=' and lhs != rhs) or # Changed '==' to '!=' +- (op == '!' and lhs == rhs) or # Changed '!=' to '==' +- (op == '>' and lhs < rhs) or # Changed '>' to '<' +- (op == '<' and lhs > rhs) or # Changed '<' to '>' +- (op == 'g' and lhs <= rhs) or # Changed '>=' to '<=' +- (op == 'l' and lhs >= rhs) # Changed '<=' to '>=' ++ (op == '=' and lhs == rhs) or ++ (op == '!' and lhs != rhs) or ++ (op == '>' and lhs > rhs) or ++ (op == '<' and lhs < rhs) or ++ (op == 'g' and lhs >= rhs) or ++ (op == 'l' and lhs <= rhs) + ) + if matched: +- return scope # Changed return value from target to scope +- raise MatchError("{0!r} {1} {2!r}", rhs, _M_OP_MAP.get(op, op), lhs) # Swapped lhs and rhs in exception ++ return target ++ raise MatchError("{0!r} {1} {2!r}", lhs, _M_OP_MAP.get(op, op), rhs) + + def __repr__(self): + op = _M_OP_MAP.get(self.op, self.op) +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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/task.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3c8e13cc8adc8736fc0438c69cfa36065af375fc --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ffd378716d402196932123dccd9479212fee36f9a5d411f792644a014e00f1be" +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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/check_pytest.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/expected-panels.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..15654e5b8590ef3c015caa8c7008d0d2d2085932 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/expected-panels.json @@ -0,0 +1,184 @@ +{ + "fail-to-pass": [ + "glom/test/test_error.py::test_all_public_errors", + "glom/test/test_match.py::test_basic", + "glom/test/test_match.py::test_match_expressions", + "glom/test/test_match.py::test_defaults", + "glom/test/test_match.py::test_m_call_match", + "glom/test/test_match.py::test_cruddy_json", + "glom/test/test_match.py::test_pattern_matching", + "glom/test/test_match.py::test_examples", + "glom/test/test_match.py::test_sky", + "glom/test/test_match.py::test_clamp", + "glom/test/test_match.py::test_check_ported_tests", + "glom/test/test_scope_vars.py::test_max_skip" + ], + "pass-to-pass": [ + "glom/test/test_basic.py::test_initial_integration", + "glom/test/test_basic.py::test_list_item_lift_and_access", + "glom/test/test_basic.py::test_coalesce", + "glom/test/test_basic.py::test_skip", + "glom/test/test_basic.py::test_stop", + "glom/test/test_basic.py::test_top_level_default", + "glom/test/test_basic.py::test_val", + "glom/test/test_basic.py::test_abstract_iterable", + "glom/test/test_basic.py::test_call_and_target", + "glom/test/test_basic.py::test_invoke", + "glom/test/test_basic.py::test_spec_and_recursion", + "glom/test/test_basic.py::test_scope", + "glom/test/test_basic.py::test_seq_getitem", + "glom/test/test_basic.py::test_beyond_access", + "glom/test/test_basic.py::test_python_native", + "glom/test/test_basic.py::test_glom_extra_kwargs", + "glom/test/test_basic.py::test_inspect", + "glom/test/test_basic.py::test_ref", + "glom/test/test_basic.py::test_pipe", + "glom/test/test_basic.py::test_api_repr", + "glom/test/test_basic.py::test_bbformat", + "glom/test/test_basic.py::test_bbrepr", + "glom/test/test_check.py::test_check_basic", + "glom/test/test_check.py::test_check_multi", + "glom/test/test_check.py::test_check_signature", + "glom/test/test_cli.py::test_cli_blank", + "glom/test/test_cli.py::test_cli_spec_target_argv_basic", + "glom/test/test_cli.py::test_cli_spec_argv_target_stdin_basic", + "glom/test/test_cli.py::test_cli_scalar", + "glom/test/test_cli.py::test_cli_spec_target_files_basic", + "glom/test/test_cli.py::test_usage_errors", + "glom/test/test_cli.py::test_main_basic", + "glom/test/test_cli.py::test_main_yaml_target", + "glom/test/test_cli.py::test_main_toml_target", + "glom/test/test_cli.py::test_main_python_full_spec_python_target", + "glom/test/test_cli.py::test_main", + "glom/test/test_error.py::test_good_error", + "glom/test/test_error.py::test_error", + "glom/test/test_error.py::test_pae_api", + "glom/test/test_error.py::test_unfinalized_glomerror_repr", + "glom/test/test_error.py::test_line_trace", + "glom/test/test_error.py::test_regular_error_stack", + "glom/test/test_error.py::test_glom_error_stack", + "glom/test/test_error.py::test_glom_error_double_stack", + "glom/test/test_error.py::test_long_target_repr", + "glom/test/test_error.py::test_branching_stack", + "glom/test/test_error.py::test_midway_branch", + "glom/test/test_error.py::test_partially_failing_branch", + "glom/test/test_error.py::test_coalesce_stack", + "glom/test/test_error.py::test_nesting_stack", + "glom/test/test_error.py::test_error_types", + "glom/test/test_error.py::test_fallback", + "glom/test/test_error.py::test_glom_dev_debug", + "glom/test/test_error.py::test_unicode_stack", + "glom/test/test_error.py::test_3_11_byte_code_caret", + "glom/test/test_fill.py::test", + "glom/test/test_grouping.py::test_bucketing", + "glom/test/test_grouping.py::test_corner_cases", + "glom/test/test_grouping.py::test_agg", + "glom/test/test_grouping.py::test_limit", + "glom/test/test_grouping.py::test_reduce", + "glom/test/test_grouping.py::test_sample", + "glom/test/test_match.py::test_match_default", + "glom/test/test_match.py::test_double_wrapping", + "glom/test/test_match.py::test_sets", + "glom/test/test_match.py::test_and_or_reduction", + "glom/test/test_match.py::test_precedence", + "glom/test/test_match.py::test_reprs", + "glom/test/test_match.py::test_shortcircuit", + "glom/test/test_match.py::test_sample", + "glom/test/test_match.py::test_regex", + "glom/test/test_match.py::test_ternary", + "glom/test/test_match.py::test_json_ref", + "glom/test/test_match.py::test_nested_struct", + "glom/test/test_match.py::test_switch", + "glom/test/test_match.py::test_nested_dict", + "glom/test/test_mutation.py::test_assign", + "glom/test/test_mutation.py::test_assign_recursive", + "glom/test/test_mutation.py::test_assign_spec_val", + "glom/test/test_mutation.py::test_unregistered_assign", + "glom/test/test_mutation.py::test_bad_assign_target", + "glom/test/test_mutation.py::test_sequence_assign", + "glom/test/test_mutation.py::test_invalid_assign_op_target", + "glom/test/test_mutation.py::test_assign_missing_signature", + "glom/test/test_mutation.py::test_assign_missing_dict", + "glom/test/test_mutation.py::test_assign_missing_object", + "glom/test/test_mutation.py::test_assign_missing_with_extant_keys", + "glom/test/test_mutation.py::test_assign_missing_unassignable", + "glom/test/test_mutation.py::test_s_assign", + "glom/test/test_mutation.py::test_delete", + "glom/test/test_mutation.py::test_unregistered_delete", + "glom/test/test_mutation.py::test_bad_delete_target", + "glom/test/test_mutation.py::test_sequence_delete", + "glom/test/test_mutation.py::test_invalid_delete_op_target", + "glom/test/test_mutation.py::test_delete_ignore_missing", + "glom/test/test_mutation.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_list_path_access", + "glom/test/test_path_and_t.py::test_path", + "glom/test/test_path_and_t.py::test_empty_path_access", + "glom/test/test_path_and_t.py::test_path_t_roundtrip", + "glom/test/test_path_and_t.py::test_path_access_error_message", + "glom/test/test_path_and_t.py::test_t_picklability", + "glom/test/test_path_and_t.py::test_t_subspec", + "glom/test/test_path_and_t.py::test_a_forbidden", + "glom/test/test_path_and_t.py::test_s_magic", + "glom/test/test_path_and_t.py::test_path_len", + "glom/test/test_path_and_t.py::test_path_getitem", + "glom/test/test_path_and_t.py::test_path_slices", + "glom/test/test_path_and_t.py::test_path_values", + "glom/test/test_path_and_t.py::test_path_items", + "glom/test/test_path_and_t.py::test_path_star", + "glom/test/test_path_and_t.py::test_star_broadcast", + "glom/test/test_path_and_t.py::test_star_warning", + "glom/test/test_path_and_t.py::test_path_eq", + "glom/test/test_path_and_t.py::test_path_eq_t", + "glom/test/test_path_and_t.py::test_startswith", + "glom/test/test_path_and_t.py::test_from_t_identity", + "glom/test/test_path_and_t.py::test_t_dict_key", + "glom/test/test_path_and_t.py::test_t_arithmetic", + "glom/test/test_path_and_t.py::test_t_arithmetic_reprs", + "glom/test/test_path_and_t.py::test_t_arithmetic_errors", + "glom/test/test_path_and_t.py::test_t_dunders", + "glom/test/test_path_and_t.py::test_path_cache", + "glom/test/test_reduction.py::test_sum_integers", + "glom/test/test_reduction.py::test_sum_seqs", + "glom/test/test_reduction.py::test_fold", + "glom/test/test_reduction.py::test_fold_bad_iter", + "glom/test/test_reduction.py::test_flatten", + "glom/test/test_reduction.py::test_flatten_func", + "glom/test/test_reduction.py::test_merge", + "glom/test/test_reduction.py::test_merge_omd", + "glom/test/test_reduction.py::test_merge_func", + "glom/test/test_scope_vars.py::test_s_scope_assign", + "glom/test/test_scope_vars.py::test_globals", + "glom/test/test_scope_vars.py::test_vars", + "glom/test/test_scope_vars.py::test_scoped_vars", + "glom/test/test_scope_vars.py::test_let", + "glom/test/test_spec.py::test_spec", + "glom/test/test_spec.py::test_scope_spec", + "glom/test/test_streaming.py::test_iter", + "glom/test/test_streaming.py::test_filter", + "glom/test/test_streaming.py::test_map", + "glom/test/test_streaming.py::test_split_flatten", + "glom/test/test_streaming.py::test_chunked", + "glom/test/test_streaming.py::test_windowed", + "glom/test/test_streaming.py::test_unique", + "glom/test/test_streaming.py::test_slice", + "glom/test/test_streaming.py::test_while", + "glom/test/test_streaming.py::test_iter_composition", + "glom/test/test_streaming.py::test_faulty_iterate", + "glom/test/test_streaming.py::test_first", + "glom/test/test_streaming.py::test_all", + "glom/test/test_target_types.py::test_types_leave_one_out", + "glom/test/test_target_types.py::test_types_bare", + "glom/test/test_target_types.py::test_invalid_register", + "glom/test/test_target_types.py::test_exact_register", + "glom/test/test_target_types.py::test_duck_register", + "glom/test/test_target_types.py::test_bypass_getitem", + "glom/test/test_target_types.py::test_iter_set", + "glom/test/test_target_types.py::test_iter_str", + "glom/test/test_target_types.py::test_default_scope_register", + "glom/test/test_target_types.py::test_faulty_iterate", + "glom/test/test_target_types.py::test_faulty_op_registration", + "glom/test/test_target_types.py::test_reregister_type", + "glom/test/test_tutorial.py::test_tutorial_data", + "glom/test/test_tutorial.py::test_tutorial" + ] +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/grade.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/panel-config.json b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6c5ce1de4028139dab5dedec5befcc5374ad1e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/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.txt" + ], + "test_dependency_source_sha256": { + "requirements.txt": "16d7397649f1e969ac936db498607f1d0793d26b5880e44053c5b804af0ebb27", + "tox.ini": "18f0932ef1cf1fa9db666fde1c40ef730ed1408dd2b9ea9e17f8b392f6523747" + } +} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/test.sh b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/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/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/__init__.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_invalid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_invalid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_valid.toml b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_valid.yaml b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/perf_report.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_basic.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_check.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_cli.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_error.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_fill.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_grouping.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_match.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_mutation.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_path_and_t.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_reduction.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_scope_vars.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_snippets.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_spec.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_streaming.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_target_types.py b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/tasks/mahmoud__glom.fb3c4e76.func_basic__39aaz49a/tests/trusted/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType'